Talking about includes and indexOf methods

The includes() method returns true or false

The indexOf() method returns -1 or the subscript index of the array where the element is located

For simple data types, if the value exists, includes returns true, and indexOf returns the subscript of the array.

let arr=[0,2,null]
console.log(arr.indexOf(2)) //返回1(2所在arr下标索引)
console.log(arr.includes(2)) //返回true

For complex data types

 let student = { name: '张三' }   //student变量存的是一个地址引用
 let stuList1 = [{ name: '张三' }] //stuList1[0]是一个值,是一个匿名对象
 let stuList2= [{ name: '李四' }, student] 
 console.log(stuList1.indexOf(student)) //返回-1
 console.log(stuList2.indexOf(student)) //返回1
 console.log(stuList1.includes(student)) //返回false
 console.log(stuList2.includes(student)) //返回true
 console.log(student === stuList1[0]) //false
 console.log(student.name == stuList1[0].name) //true

 

Guess you like

Origin blog.csdn.net/qq_30596783/article/details/120327984