命令式 vs 函数式 vs 链式

这里用 For 循环举例

命令式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13

const files = ["foo.txt ", ".bar", "   ", "baz.foo"];
let filePaths = [];

for (let file of files) {
  const fileName = file.trim();
  if (fileName) {
    const filePath = `~/cool_app/${fileName}`;
    filePaths.push(filePath);
  }
}

// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']

函数式

封装性更好

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12

const files = ["foo.txt ", ".bar", "   ", "baz.foo"];
const filePaths = files.reduce((acc, file) => {
  const fileName = file.trim();
  if (fileName) {
    const filePath = `~/cool_app/${fileName}`;
    acc.push(filePath);
  }
  return acc;
}, []);

// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']

链式

与函数式相比,更直观,也是建议使用的方式

1
2
3
4
5
6
7
8

const files = ["foo.txt ", ".bar", "   ", "baz.foo"];
const filePaths = files
  .map((file) => file.trim())
  .filter(Boolean)
  .map((fileName) => `~/cool_app/${fileName}`);

// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
此页面上有什么