为什么数组中有空项目?如何清除它们? [英] Why are empty items in my array and how do I get rid of them?
本文介绍了为什么数组中有空项目?如何清除它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Visual Studio Code。我正在尝试使用JavaScript返回仅包含奇数的数组。这是代码:
I am using Visual Studio Code. I am trying to return an array with only odd numbers using JavaScript. This is the code:
function oddCouple(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
delete arr[i];
}
}
return arr;
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
这就是我得到的。我不想要空项目,只希望是奇数。
This is what I am getting. I do not want the empty items, just odd numbers.
[ <2 empty items>, 7, <1 empty item>, 1, 3, 7, 5 ]
推荐答案
删除
运算符删除对象的属性。这是具有数组值的索引。结果是稀疏数组。
要获取没有某些项目的数组,可以过滤该数组。
For getting an array without some items, you could filter the array.
function oddCouple(array) {
return array.filter(v => v % 2);
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
需要相同的数组引用,则可以使用 Array#splice
并从末尾迭代数组,因为在拼接项目后索引会发生变化。
Or if you need the same array reference, then you could use Array#splice
and iterate the array from the end, because the index is changing after splicing the item.
function oddCouple(array) {
var i = array.length;
while (i--) {
if (array[i] % 2 === 0) {
array.splice(i, 1);
}
}
return array;
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
这篇关于为什么数组中有空项目?如何清除它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文