簡體   English   中英

在jquery中如何通過索引[“key”]或值刪除數組元素

[英]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. 雖然這只是一個例子,正如@Eric指出的那樣,修改對象的原型並不是一個好主意。 所以我重寫了不改變對象狀態的例子
  2. 添加了檢查元素是否存在於數組中的情況。 如果它不存在,則reeturned索引將為-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}

根據您的代碼判斷,聽起來您想要刪除對象的屬性,您可以使用delete來執行此操作:

var obj = { key: "value" };

delete obj["key"];

可以在MDN上找到有關在JavaScript中使用對象的非常有用的指南。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM