[英]In jquery how do I remove an array element either via index[“key”] or value
在jQuery / JavaScript中 ,如何刪除數組元素?
就像是:
array.remove(array["key"]);
// or
array.remove("value")
對於數組,使用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]
如果要從對象中刪除項,請使用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}
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1);
將從陣列水果中移除1個項目,位置2,即Apple
array["key"]
不是數組的鍵(javascript中沒有關聯數組,如果你來自PHP,它們可能看起來像它們,但它們是對象)但是對象的屬性,我想你可以使用刪除
delete array.key
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.