本篇文章给大家简单对比一下javascript中的includes() 和 indexof()方法,聊聊它们有什么区别,希望对大家有所帮助!
1、基本区别
includes()和indexof()都是用来检查数组是否包含某些元素,includes()返回值是布尔值,indexof()返回的是索引值,如果没有返回-1。【相关推荐:javascript学习教程】
let arr = [1,2,3]arr.indexof(0) // -1arr.indexof(2) // 1arr.includes(2) // true
2、检查nan和undefined
因为indexof()是严格按照===操作符来做值的比较,所以indexof()不能检查nan,但是includes()可以
let arr = [nan,]arr.indexof(nan) // -1arr.indexof(undefined) // -1arr.includes(nan) // truearr.includes(undefined) // true
3、检查-0和+0
includes()和indexof()没有区分-0和+0,在判断时,认为二者是相同的
let arr = [+0]arr.includes(-0) // truearr.indexof(-0) // 0
4、不能检查复杂数据类型
二者只能判断简单数据类型,对于对象、数组等复杂数据类型是不可以判断的
let arr = [{a:1},{a:2}]arr.includes({a:1}) // falsearr.indexof({a:1}) // -1
5、indexof()可用于字符串
返回指定字符第一次出现的位置,并且存在有隐式转换
let str = 'a1b2c3'str.indexof('2')); //3str.indexof(1)); //3
更多编程相关知识,请访问:编程视频!!
以上就是js中 includes() vs indexof(),聊聊它们有什么区别的详细内容。