[英]Function to imitate Java's ArrayList.remove(o)
How can I implement a function that does the same thing as ArrayList.remove(o)
? 如何实现与
ArrayList.remove(o)
相同的功能?
The closest thing I have is 我最近的东西是
Array.prototype.remove = function(o) {
var index = this.indexOf(o);
if(index == -1) {
return;
}
return this.splice(index, index);
}
However it throws an error on the second line, claiming indexOf(o)
doesn't exist. 但是,它在第二行引发了错误,声称
indexOf(o)
不存在。 ( cannot find function indexOf()
) (
cannot find function indexOf()
)
Array.prototype.indexOf
is not supported by IE7 and below. IE7及更低版本不支持
Array.prototype.indexOf
。 So you would need to shim that method aswell before, like 因此,您还需要像之前那样匀化该方法
Array.prototype.indexOf = Array.prototype.indexOf || function( search ) {
for(var i = 0, len = this.length; i < len; i++) {
if( this[ i ] === search ) {
return i;
}
}
return -1;
};
(simplified example) . (简化示例) 。
Furthermore, your call to .splice()
is wrong, second argument is the length of elements you want to remove and it should be 1
. 此外,您对
.splice()
调用是错误的,第二个参数是要删除的元素的长度,应为1
。
Array.prototype.remove = function(o) {
var index = this.indexOf(o);
if(~index) {
this.splice(index, 1);
}
};
Another idea would be to use and "associative array", aka object literal with name value pairs and use the delete operator which works in all modern browsers. 另一个想法是使用“关联数组”,也就是带有名称值对的对象文字,并使用在所有现代浏览器中均可使用的delete运算符。
var arr = {'x': somval, 'y': someval2 ...}
delete arr.x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.