每天前端,includes(), some(), es6扩展运算符

利用数组进行判断的代码更优雅

 includes函数

使用前

if (fruit === 'apple' || fruit === 'orange' || fruit === 'grape') {
  //...
}

使用后

if (['apple', 'orange' ,'grape'].includes(fruit)) {
  //...
}

还有类似的some()函数,通过回调方法进行判断

只要数组中任意1个元素满足条件即返回true, 全无返回false

例如

 const arry = [1, 1, 2, 2]
 const bl = this.arry.some(e => {
        return (e - 1) === 1
      })
console.log(bl) // true

 

在es6中使用扩展运算符,能更好操作数组

例如

假设要去重一个数组
let arry = new Set([1, 1, 2, 2])  //

但这时并不是一个完全的数组需要重新push,则可以使用扩展运算符
let new_arry = [...arry] // [1 , 2]


支持push, 更方便合并
[
1, 2, ...arry] // [1, 2, 1, 2] let arr = [0, 1] let arr2 = [8, 9]
arr.push(...arr2) // [0, 1, 8, 9] [...arr, ...arr2]
// [0, 1, 8, 9]

 

posted @ 2020-06-12 09:37  小萌豚  阅读(1885)  评论(0编辑  收藏  举报