【问题标题】:JavaScript - Replacing for loop with array helpersJavaScript - 用数组助手替换 for 循环
【发布时间】:2018-09-16 05:09:24
【问题描述】:

所以今天我正在学习一些 ES6 数组助手,我想用它们来改变我现有的 for 循环,但是我不能得到与 for 循环相同的结果

function comment(){
    let index;
    for(let i = 0; i < commentArray.length; i++){
        if(commentArray[i]._id == req.params.commentId){
            index = commentArray.indexOf(commentArray[i]);
        }
    }
    return index;
}
var com = comment();

它是nodejs,我正在尝试从数据库中获取元素索引,而不是从中提取,我的代码工作得很好,但我想用数组助手来改变它,我想我需要find helper,但我不能让它起作用!

【问题讨论】:

  • 你的“数组助手”代码是什么?

标签: javascript arrays node.js ecmascript-6


【解决方案1】:

你可以用这个使用Array#findIndex的单行代码替换你的for循环:

let index = commentArray.findIndex(comment => comment._id === req.params.commentId);

当这行执行时,它会分配comment的索引,它的_id属性与req.params.commentId相同。

【讨论】:

  • 效果很好!只需将三重等号更改为双倍,因为当索引等于-1时,三重等号会给我带来愚蠢的错误,我猜这是因为comment._id来自db作为字符串
  • @TokoGoshadze -- 不要混淆。阅读差异here,然后做出决定。
【解决方案2】:

如果你想根据某些条件在数组中找到项的索引,你可以使用findIndex函数

commentArray.findIndex(comment => comment._id === req.params.commentId)

还有你当前的代码for loop,我认为你需要在找到索引后立即返回,不要让循环迭代到最后。

for(let i = 0; i < commentArray.length; i++){
    if(commentArray[i]._id == req.params.commentId){
        return commentArray.indexOf(commentArray[i]);
    }
}

【讨论】:

  • 感谢您的回答,它成功了,记住下次找到时返回索引!
猜你喜欢
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多