简体   繁体   English

如何用forEach替换javascript for循环并获取每次迭代的索引?

[英]How can I replace a javascript for loop with a forEach and get access to the index for each iteration?

I have this Javascript: 我有这个Javascript:

factory.remove = function (arr, property, num) {
    for (var i = arr.length - 1; i >= 0; --i) {
        if (arr[i][property] === num)
            arr.splice(i, 1);
    }
};

Can someone tell me how I could change the for loop to use a .forEach instead? 有人能告诉我如何更改for循环以使用.forEach吗? What I am not sure about is how in the forEach I can access the i ? 我不确定的是,在每个我可以访问i如何? Also if I use the forEach will I be able to do a splice of that array or is it not possible? 另外,如果我使用forEach,我可以对该数组进行拼接,还是不可能?

This code 这段代码

for (var i = arr.length - 1; i >= 0; --i) {
        if (arr[i][property] === num)
            arr.splice(i, 1);
    }

could be written like this 可以写成这样的

arr.forEach(function(elem,index){
    if(elem[property]===num)
       arr.splice(index, 1);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM