[英]Remove specific elements from array
i got this code : 我得到了这个代码:
Object.defineProperty(Array.prototype, "remove", {
enumerable: false,
value: function (item) {
var removeCounter = 0;
for (var index = 0; index < this.length; index++) {
if (this[index] === item) {
this.splice(index, 1);
removeCounter++;
index--;
}
}
return removeCounter;
}
});
And i try to remove from array specific elements with this code line : 我尝试使用此代码行从数组特定元素中删除:
var itemsRemoved = finalArray.remove(getBack);
But if i do console.log() it return 0 elements removed while my variable getBack is equal with 0 or other number and in array getBack value exists. 但是如果我做console.log()它返回0个元素,而我的变量getBack等于0或其他数字,并且数组中存在getBack值。
Use item.indexOf(this[index])
instead of this[index] === item
. 使用
item.indexOf(this[index])
代替this[index] === item
。
Why? 为什么?
item
is an Array and not a single Value: item
是一个数组而不是单个值:
Object.defineProperty(Array.prototype, "remove", {
enumerable: false,
value: function (item) {
var removeCounter = 0;
for (var index = 0; index < this.length; index++) {
console.log(this[index], item);
if (item.indexOf(this[index]) > -1) {
this.splice(index, 1);
removeCounter++;
index--;
}
}
return removeCounter;
}
});
See this thread about object comparison in js 请参阅此线程以了解js中的对象比较
A quick way to achieve it : 一种快速的方法:
Object.defineProperty(Array.prototype, "remove", {
enumerable: false,
value: function (item) {
var removeCounter = 0;
for (var index = 0; index < this.length; index++) {
if (JSON.stringify(this[index]) === JSON.stringify(item)) {
this.splice(index, 1);
removeCounter++;
index--;
}
}
return removeCounter;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.