美文网首页
Javascript 数组遍历方法总结:find、filter、

Javascript 数组遍历方法总结:find、filter、

作者: fourn熊能 | 来源:发表于2019-03-12 14:35 被阅读0次

    array.find(function (value, index, arr){}, thisValue)

    为数组中的每个元素都调用一次函数执行,当前元素在测试函数中返回了true,find会返回符合条件的元素,之后不会再继续执行。如果没有符合条件的返回undefined。
    例如:

    // 在权限数组中查找是否存在当前权限
    if (perms.find(perm => perm.name === targetPerm)) {
        return true
    }
    

    array.filter(function (value, index, arr){}, thisValue)

    筛选数组中符合条件的所有元素,并且放在一个新数组中,如果没有,返回一个空数组。
    例如:

    // 从回复列表中剔除已经被删除的回复
    this.replies = this.replies.filter((reply) => reply.id !== replyId)
    

    array.map(function(value, index, arr), thisValue)

    对数组中的元素调用函数进行处理,并且把处理结果放在一个新数组中返回,如果没有返回值,新数组中的每一个元素都为undefined。
    例如:

    // 格式化回复记录的创建时间,replies整个会被重新赋值
    replies = replies.map((reply) => {
        reply.created_at_diff = util.diffForHumans(reply.created_at)
        return reply
    })
    

    array.forEach(function(value, index, arr), thisValue)

    用于对数组中的每一个元素执行一次回调函数,但它没有返回值,或者说它的返回值为undefined,即便我们在回调函数中写了return语句,返回值依然为undefined。注意没有办法跳出或终止forEach语句,除非抛出异常。
    例如:

    // 格式化回复记录的创建时间,replies中相应的记录在每次执行时会被重新赋值
    replies.forEach((reply) => {
        reply.created_at_diff = util.diffForHumans(reply.created_at)
    })
    

    • value:必须,当前元素
    • index:当前索引值
    • arr:当前的数组
    • thisValue:this值,默认undefined

    相关文章

      网友评论

          本文标题:Javascript 数组遍历方法总结:find、filter、

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