JavaScript简写小技巧(1)

循环

for (let i = 0; i < allImgs.length; i++)
简写
for (let index of allImgs)

Array.find

使用了遍历数组寻找,可以Array.find函数。

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
  for(let si = 0; si<pets.length; ++si) {
    if(pets[si].type === 'Dog' && pets[si].name === name) {
      return pets[si];
    }
  }
}

简写为:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

原文连接:https://www.sitepoint.com/shorthand-javascript-techniques/

猜你喜欢

转载自blog.csdn.net/RAYFUXK/article/details/81561133
今日推荐