问题
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 ]
回答1:
You need to use splice() instead of delete because delete doesn't change the length of the array. But be careful using splice() in a for loop because you alter the array as you're looping through it, which doesn't work well.
An alternative is to loop backwards:
function oddCouple(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] % 2 == 0) {
arr.splice(i, 1);
}
}
return arr;
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
Of course a still better alternative is to use filter(), but note this doesn't change the original array.
function oddCouple(arr) {
return arr.filter(i => i % 2)
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
回答2:
The delete operator deletes a property of an object. This is the index with the value for an array. The result is a sparse array.
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]));
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]));
回答3:
The delete function removes the content of the item but keeps an empty slot.
You need the splice method to remove an element without leaving an empty slot.
arr.splice(i, 1);
回答4:
You can return the array by filtering truthy values:
function oddCouple(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
delete arr[i];
}
}
return arr.filter(r=>r);
}
console.log(oddCouple([2, 6, 7, 0, 1, 3, 7, 5]));
Rather, I can do simply:
const arr = [2,6,7,0,1,3,7,5]
console.log(arr.filter(r=>r%2!=0))
//or,
console.log(arr.filter(r=>r%2)) // !=0
来源:https://stackoverflow.com/questions/51688366/why-are-empty-items-in-my-array-and-how-do-i-get-rid-of-them