gpt4 book ai didi

javascript - 从第一个索引中按顺序删除数组 javascript 值

转载 作者:行者123 更新时间:2023-11-30 09:15:11 25 4
gpt4 key购买 nike

我有这个数组:

let items = ["apple", "orange", "watermelon", "blueberry", "lemon", "guava"];

我想从第一个索引中按顺序删除数组值。所以它会产生:

[ "apple", "orange", "watermelon", "blueberry", "lemon", "guava" ]
[ "orange", "watermelon", "blueberry", "lemon", "guava" ]
[ "watermelon", "blueberry", "lemon", "guava" ]
[ "blueberry", "lemon", "guava" ]
[ "lemon", "guava" ]
[ "guava" ]

我已经尝试过这段代码:

let items = ["apple", "orange", "watermelon", "blueberry", "lemon",   "guava"];

runLoop = async () => {
for(const item of items){
await new Promise( resolve => setTimeout( resolve, 1000 ));
console.log(items);
remove(items, item);
console.log('------------');
}
}

function remove(array, element) {
console.log('deleting '+element);
const index = array.indexOf(element);
array.splice(index, 1);
}

但结果不是我所期望的,这是结果:

Array(6) [ "apple", "orange", "watermelon", "blueberry", "lemon", "guava" ]
Array(5) [ "orange", "watermelon", "blueberry", "lemon", "guava" ]
Array(4) [ "orange", "blueberry", "lemon", "guava" ]

最佳答案

问题是可迭代数组是事件的 - 如果您使用 for..of 调用迭代器并在迭代器仍在使用时改变数组 ,迭代的结果项可能不直观 - 可能会遗漏一些指标。这有点像这里发生的事情:

let items = ["apple", "orange", "watermelon", "blueberry", "lemon",   "guava"];
for (let i = 0; i < items.length; i++) {
console.log('item: ', items[i]);
items.splice(i, 1);
}

循环只运行 3 次,因为您在遍历数组时从数组中删除了项目,所以一些指标会被跳过。

一种可能性是在用 for..of 调用迭代器时首先复制数组,这样迭代器将始终迭代原始数组中的每个项目数组顺序:

let items = ["apple", "orange", "watermelon", "blueberry", "lemon",   "guava"];

runLoop = async () => {
for(const item of items.slice()){
await new Promise( resolve => setTimeout( resolve, 300 ));
console.log(items);
remove(items, item);
console.log('------------');
}
}

function remove(array, element) {
console.log('deleting '+element);
const index = array.indexOf(element);
array.splice(index, 1);
}
runLoop();

关于javascript - 从第一个索引中按顺序删除数组 javascript 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com