for of,reduce,链式编程

[JS 编程技巧] for of,reduce,链式编程.

1
2
3
4
5
// 需求
// input
// files = [ 'foo.txt ', '.bar', ' ', 'baz.foo' ];
// output
// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
1
const files = ["foo.txt ", ".bar", "   ", "baz.foo"];

方法 1: loop 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function forLoop() {
const result = [];
for (const file of files) {
const fileName = file.trim();
if (fileName) {
const filePath = `~/cool_app/${fileName}`;
result.push(filePath);
}
}
console.log(result);
return result;
}

forLoop();

方法 2: reduce方法

1
2
3
4
5
6
7
8
9
10
11
12
function reduceWay() {
const filePath = files.reduce((result, file) => {
const fileName = file.trim();
if (fileName) {
const filePath = `~/cool_app/${fileName}`;
result.push(filePath);
}
return result;
}, []);
console.log(filePath);
}
reduceWay();

方法 3: 链式调用

1
2
3
4
5
6
7
8
9
10
function chain() {
// 链式调用方法,一个方法只做一件事情.
const filePaths = files
.map((f) => f.trim())
.filter(Boolean)
.map((fileName) => `~/cool_app/${fileName}`);

console.log(filePaths);
}
chain();

控制台测试截图:

控制台