Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于Array.prototype.includes #1

Open
lensh opened this issue Jul 21, 2017 · 0 comments
Open

关于Array.prototype.includes #1

lensh opened this issue Jul 21, 2017 · 0 comments

Comments

@lensh
Copy link
Owner

lensh commented Jul 21, 2017

这是ES7新增的判断数组里面是否存在某个值的方法,存在时返回true,否则返回false。
例如:const arr=[1,3,4,5,6] ,那么arr.includes(3)将返回true,因为包含了数字3
值得注意的是,如果该值是一个非空对象,那么无论怎么判断,都是返回false的。

const arr=[{name:'zls'}]
console.log(arr.includes({name:'zls'}))   // false,注意这里是返回false

其它基本数据类型都是返回true,所有测试用例如下:

   const arr=[1]
   console.log(arr.includes(1))  // true
   const arr1=[true,false]
   console.log(arr1.includes(true))   //true
   const arr2=[undefined]
   console.log(arr2.includes(undefined))   // true
   const arr3=['str']
   console.log(arr3.includes('str'))   // true
   const arr4=[null]
   console.log(arr4.includes(null))   // true
   const arr5=[{name:'zls'}]
   console.log(arr5.includes({name:'zls'}))   // false

如果我们要判断数组里是否存在某个对象,我们可以使用arr.find()或者arr.findIndex(),
例如 const arr=[{name:'zls'}],如果要判断这个arr数组里是否包含 {name:'zls'},可以这样:

const index=arr.findIndex((item)=>{
   return item.name='zls'
})
//   index为0,在第0个位置,所以是存在的
@lensh lensh changed the title 关于Array.prototype.includes的局限性 关于Array.prototype.includes Jul 23, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant