[英]How to remove all the odd indexes (eg: a[1],a[3]..) value from the array
[英]forEach array, if value is odd remove from array
我正在嘗試使用以下代碼從我的數組中刪除所有偶數編號的項目:
var myArray = [1,2,3,4,5,6];
myArray.forEach(function(item) {
if (item%2 == 0) {
myArray.splice(item);
}
});
我認為拼接處錯了嗎?
你可以這樣:
var myarray = [1,2,3,4,5,6]
filtered = myarray.filter(function(el, index) {
return index % 2 === 1;
});
輸出:[2,4,6]
您應該這樣進行:
var myArray = [1,2,3,4,5,6];
myArray.forEach(function(item, x) {
if (item%2 == 0)
myArray.splice(x, 1); // Remove 1 item from index x
});
或使用.filter
(IE8 +)的更好方法
var myArray = myArray.filter(function(item) {
return item % 2 ==0 ? false : true; // Return false if item is even and true other way round.
});
是的,拼接是通過索引完成的
var myArray = [1,2,3,4,5,6];
myArray.forEach(function(item) {
if (item%2 == 0) {
var index = myArray.indexOf(item);
myArray = myArray.splice(index,1);
}
});
filter()
會更好
var arr = myArray.filter(function(item) {
return item % 2 ==0 ? true : false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.