I've been able to figure out splicing using a 'for' loop and a 'for in' loop, but not a 'for of' loop. 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()
.
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++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.