简体   繁体   中英

Extending Array with custom method that removes an element by value

I have to make a new array method, that when called it removes a specific 'value' from an array. It works with numbers, but when I use a string it returns an empty array...

 Array.prototype.removeItem = function(value){ for(var key in this){ this.splice(this.indexOf(value), 1); } } var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, '1']; console.log(arr); arr.removeItem(1); console.log(arr); var arrSecond = ['hi', 'bye', 'hello' ]; console.log(arrSecond); arrSecond.removeItem('hi'); console.log(arrSecond); 

If value isn't found, indexOf will return -1. A negative start passed to splice is counted from the end. See ECMA-262 §15.4.4.14

So once you remove the value from the array, after that you are removing the last member.

A better method might be something like:

var index;
while ((index = this.indexOf(value)) > -1) {
  this.splice(index, 1);
}

for..in should not be used here, consider forEach for Array loops instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM