我有这个数组:
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" ]
答案 0 :(得分:3)
问题在于数组可迭代是 live -如果您使用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();
答案 1 :(得分:1)
您需要在索引零处拼接
array.splice(0, 1);
或仅移动第一个元素。
array.shift();
答案 2 :(得分:0)
可以使用递归函数和shift来替代数组中的第一个元素
let items = ["apple", "orange", "watermelon", "blueberry", "lemon", "guava"];
function removeElem(arr) {
if (arr.length !== 1) {
console.log(arr)
arr.shift();
removeElem(arr)
} else {
console.log(arr)
}
}
removeElem(items)
答案 3 :(得分:0)
您可以使用Array.slice实现此目的。使用拼接时,请记住它将影响原始数组,根据javascript的功能方法,不应这样做。函数式编程不建议对原始对象进行变异。
let items = ["apple", "orange", "watermelon", "blueberry", "lemon", "guava"];
for(let i=0;i<items.length;i++){
console.log(items.slice(i,items.length));
}