loops/reduce/方法链 处理数组对比
作者:互联网
loops 循环
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']
Array reduce
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']
Method chaining 方法链
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']
标签:const,app,reduce,fileName,数组,filePaths,loops,foo,cool 来源: https://www.cnblogs.com/sunr/p/16664043.html