美文网首页ES6
JS中find(), findIndex(), some(),

JS中find(), findIndex(), some(),

作者: 小二哥很二 | 来源:发表于2020-06-15 15:40 被阅读0次
1、find()用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined
const books = [1,2,-33,-1,-2,4,5]
document.getElementById('test').innerHTML = books.find((n) => n<0)
结果:-33
2、findIndex()和find()类似
获取books对象里元素item的id是否跟参数id相等
removeHandle(id) {
      // 第一种方法
      // this.books.splice(index-1, 1)
      // 第二种方法
      let index = this.books.findIndex(item =>{
        return item.id == id;
      });
      console.log(index);   // 返回的是正常索引值,不用-1
      // 根据索引删除数组元素
      this.books.splice(index, 1)
    }
3、every()与some()方法都是JS中数组的迭代方法, 只返回布尔值。

every():是判断数组中每个元素都满足条件
some():判断数组中是否至少有一个元素满足条件

var arr1=[1, 2, 3, 4, 5];
var arr2=[1, 4, 6, 8, 10];
console.log(
    arr1.every(function(value, index, array){
        return value % 2 == 0;
    })
);    // false
console.log(
    arr2.some(function(value, index, array){
        return value % 2 == 0;
    })
);

相关文章

网友评论

    本文标题:JS中find(), findIndex(), some(),

    本文链接:https://www.haomeiwen.com/subject/nvxhxktx.html