indexOf(a,b)是在es6之前常用的判断数组/字符串内元素是否存在的api,接收两个参数,第一个a代表要被查找的元素,必填。第二个代表从数组的某个坐标开始查找,可选

在数组中

通过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
复制代码

在字符串中

与数组中比较区别主要有两点:

  1. 字符串使用indexOf第二个参数不接受-1
const a = [1, 2, 3]
let b = 2
console.log(a.indexOf(b,-1) !== -1) // false
复制代码
  1. 字符串使用第一个参数,会默认转成字符串
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最大的区别在于:

1.能过识别NaN是否存在数组中

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
复制代码