ES7(一) —— includes 目錄

目錄

  • 數組如何判斷元素是否存在?
    • ES5 indexOf
    • ES5 filter
    • ES6 find
    • ES7 includes
  • Array.prototype.includes
  • ES6-ES10學習版圖

數組如何判斷元素是否存在?

ES5 indexOf

數組中有的返回下標,沒有的返回-1,但是其無法查找數組中的NaN

const arr = ['foo', 1, NaN, false]
console.log(arr.indexOf('foo'))  // 0
console.log(arr.indexOf('bar'))  // -1
console.log(arr.indexOf(NaN))  // -1

ES5 filter

array1.filter(function (item) { return item === 2 }).length > 0

ES6 用find

array1.find(function (item) { return item === 2 })

ES7 includes

Array.prototype.includes

Array.prototype.includes()

方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false。

const arr = [1,2,3,4,5,7]

console.log(arr.includes(4)) // true
console.log(arr.includes(40)) // false

PS:indexOf無法查找NaN,使用includes可以查找NaN

ES6-ES10學習版圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章