indexOf(a,b)是在es6以前經常使用的判斷數組/字符串內元素是否存在的api,接收兩個參數,第一個a表明要被查找的元素,必填。第二個表明從數組的某個座標開始查找,可選es6
在數組中api
經過indexOf,會返回元素在array中的位置,不存在就返回-1數組
const a = [1, 2, 3]
let b = 2
console.log(a.indexOf(b) !== -1) // true
console.log(a.indexOf(b,2) !== -1) // false
複製代碼
在字符串中bash
與數組中比較區別主要有兩點:ui
const a = [1, 2, 3]
let b = 2
console.log(a.indexOf(b,-1) !== -1) // false
複製代碼
const a = ["1", "2", "3"]
const b = "123"
let c = 2
console.log(a.indexOf(c) !== -1) // false
console.log(b.indexOf(c) !== -1) // true
複製代碼
includes僅能用來判斷元素是否存在。其用法與indexOf相似,都能做用在字符串中,一樣在字符串中includes不接受-1座標而且能默認轉換字符串。可是,與indexOf最大的區別在於:spa
1.能過識別NaN是否存在數組中code
const a = [NaN,NaN,NaN]
console.log(a.indexOf(NaN) !== -1) // false
console.log(a.includes(NaN) !== -1) // true
複製代碼
2.判斷稀疏數組內元素字符串
const a = [,,NaN]
console.log(a.indexOf(undefined) !== -1) // false
console.log(a.includes(undefined) !== -1) // true
複製代碼