每天前端,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]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM