nitroge / memories

日常学习累积的点点滴滴滴滴点点
7 stars 0 forks source link

for循环,reduce和方法链 #2

Open nitroge opened 3 years ago

nitroge commented 3 years ago

原文请戳这里!!

For 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;
}, []);

Method chaining

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