Open nitroge opened 3 years ago
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']
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; }, []);
const files = [ 'foo.txt ', '.bar', ' ', 'baz.foo' ]; const filePaths = files .map(file => file.trim()) .filter(Boolean) .map(fileName => `~/cool_app/${fileName}`)
原文请戳这里!!
For loops
Array reduce
Method chaining