在jQuery/JavaScript,中如何删除数组元素?
类似于:
array.remove(array["key"]);
// or
array.remove("value")
发布于 2012-06-23 23:50:04
发布于 2012-06-23 23:51:15
对于阵列,请使用splice方法:
var array = [1, 2, 3, 4, 5];
array.splice(2, 1);
console.log(array); // [1, 2, 4, 5]
您可以创建自己的函数来删除(第一次出现的)数组中的某个元素:
Array.prototype.remove = function(el) {
return this.splice(this.indexOf(el), 1);
}
var arr = [1, 2, 3, 4, 5];
arr.remove(4);
console.log(arr); // [1, 2, 3, 5]
如果要从object中删除项目,请使用delete
语法:
var a = {key1: 'val1', key2: 'val2'};
delete a.key1;
console.log(a); // {key2: 'val2'}
同样,您可以创建自己的函数来处理此问题:
Object.prototype.remove = function(el) {
if (this.hasOwnProperty(el)) {
delete this[el];
}
return this;
}
var a = {key1 : 'val1', key2: 'val2'};
a.remove('key1');
console.log(a); // {key2: 'val2'}
更新:
-1
,splice方法将删除最后一个元素(数组末尾的第一个元素)。谢谢,@amnotiam!function remove(collection, key) {
// if the collections is an array
if(collection instanceof Array) {
if(collection.indexOf(key) != -1) {
collection.splice(collection.indexOf(key), 1);
}
}
// it's an object
else if(collection.hasOwnProperty(key)) {
delete collection[key];
}
return collection;
};
当然,由于问题被标记为jquery
,我们可以将此函数添加为jquery插件:
(function($, global, undefined) {
$.removeElementFromCollection = function(collection,key) {
// if the collections is an array
if(collection instanceof Array) {
// use jquery's `inArray` method because ie8
// doesn't support the `indexOf` method
if($.inArray(key, collection) != -1) {
collection.splice($.inArray(key, collection), 1);
}
}
// it's an object
else if(collection.hasOwnProperty(key)) {
delete collection[key];
}
return collection;
};
})(jQuery, window);
然后像这样使用它:
var array = [1, 2, 3, 4, 5];
$.removeElementFromCollection(array, 2); // [1, 3, 4, 5]
var object = {1: 2, 3: 4};
$.removeElementFromCollection(object, 1); // {3: 4}
发布于 2012-06-23 23:50:43
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1);
将从fruits数组中删除1项,位置2,即Apple
https://stackoverflow.com/questions/11170825
复制相似问题