js中 判断数组 是否包含某元素
四个API ,判断包含某元素:
1. Array.indexOf() --推荐,Array.indexOf("x")== -1,则不包含,不返回-1 则包含
2.Array.find()
3.Array.findIndex()
4.for 或 foreach 循环,然后 if 判断
1.Array.indexOf()
- var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
-
- console.log(beasts.indexOf('bison'));
- // expected output: 1
-
- // start from index 2
- console.log(beasts.indexOf('bison', 2));
- // expected output: 4
-
- console.log(beasts.indexOf('giraffe'));//不包含,则返回-1
- // expected output: -1
详细教程: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
2.Array.find()
- var array1 = [5, 12, 8, 130, 44];
-
- var found = array1.find(function(element) {
- //条件
- return element > 10;
- });
-
- console.log(found);//返回第一个,符合条件的元素
- // expected output: 12
详细教程: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
3.Array.findIndex()
- var array1 = [5, 12, 8, 130, 44];
-
- function isLargeNumber(element) {
- return element > 13;
- }
-
- //类型上面,但是返回的是下标
- console.log(array1.findIndex(isLargeNumber));
- // expected output: 3
详细教程: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
4.for 或 foreach 循环,然后 if 判断
- var arr = [1, 5, 10, 15];
- //for循环
- for(let i=0; i<arr.length; i++) {
- if(arr[i] === 5) {
- //包含该元素
- }
- }
- // for...of
- for(v of arr) {
- if(v === 5) {
- //包含该元素
- }
- }
- //forEach
- arr.forEach(v=>{
- if(v === 5) {
- //包含该元素
- }
详细教程: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array