sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

js中 判断数组 是否包含某元素

四个API ,判断包含某元素:

1. Array.indexOf()  --推荐,Array.indexOf("x")== -1,则不包含,不返回-1 则包含

2.Array.find()

3.Array.findIndex()

4.for 或 foreach 循环,然后 if 判断

1.Array.indexOf()

  1. var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
  2. console.log(beasts.indexOf('bison'));
  3. // expected output: 1
  4. // start from index 2
  5. console.log(beasts.indexOf('bison', 2));
  6. // expected output: 4
  7. console.log(beasts.indexOf('giraffe'));//不包含,则返回-1
  8. // expected output: -1

详细教程: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

2.Array.find()

  1. var array1 = [5, 12, 8, 130, 44];
  2. var found = array1.find(function(element) {
  3. //条件
  4. return element > 10;
  5. });
  6. console.log(found);//返回第一个,符合条件的元素
  7. // expected output: 12

详细教程: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

3.Array.findIndex()

  1. var array1 = [5, 12, 8, 130, 44];
  2. function isLargeNumber(element) {
  3. return element > 13;
  4. }
  5. //类型上面,但是返回的是下标
  6. console.log(array1.findIndex(isLargeNumber));
  7. // expected output: 3

详细教程: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

4.for 或 foreach 循环,然后 if 判断

  1. var arr = [1, 5, 10, 15];
  2. //for循环
  3. for(let i=0; i<arr.length; i++) {
  4. if(arr[i] === 5) {
  5. //包含该元素
  6. }
  7. }
  8. // for...of
  9. for(v of arr) {
  10. if(v === 5) {
  11. //包含该元素
  12. }
  13. }
  14. //forEach
  15. arr.forEach(v=>{
  16. if(v === 5) {
  17. //包含该元素
  18. }

详细教程: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

https://blog.csdn.net/weixin_42144379/article/details/89510533
posted on 2022-04-10 16:46  sunny123456  阅读(367)  评论(0编辑  收藏  举报