简体   繁体   English

是否可以在JavaScript中使用“ for of”循环从数组中拼接项目?

[英]Is it possible to splice an item from an array using a 'for of' loop in javascript?

I've been able to figure out splicing using a 'for' loop and a 'for in' loop, but not a 'for of' loop. 我已经能够找出使用'for'循环和'for in'循环的拼接,而不是使用'for of'循环的拼接。 Is it possible? 可能吗? Here's my starting code... any ideas what I can change to make it work? 这是我的起始代码...有什么想法我可以更改以使其起作用?

let array = [ 'a', 'b', 'c' ];
function remove( letter ){
    for( let item of array ){
        if( item === letter ){
            parkedCars.splice ( item, 1 );
        }
    }
}
remove( 'b' );
console.log( array );

You could use for...of loop on Array.prototype.entries() and then check value and remove item by index using splice() . 您可以在Array.prototype.entries()上使用for...of循环,然后使用splice()检查值并按索引删除项目。

 let array = ['a', 'b', 'c']; function remove(arr, letter) { for (let [index, item] of arr.entries()) { if (item === letter) arr.splice(index, 1); } } remove(array, 'b'); console.log(array); 

Well, you can track the index yourself, it's not very pretty though. 好吧,您可以自己跟踪索引,尽管它不是很漂亮。

let index = 0;
for( let item of array ){
    if( item === letter ){
        parkedCars.splice ( index, 1 );
    }
    index++;
}

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

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