在 jquery 中,如何通过索引[“键”] 或值删除数组元素

In jquery how do I remove an array element either via index["key"] or value

本文关键字:数组元素 删除 jquery 索引 何通过      更新时间:2023-09-26

jQuery/JavaScript中,如何删除数组元素?

像这样:

array.remove(array["key"]);
// or 
array.remove("value")

从您的代码来看,听起来您想删除对象的属性,您将使用 delete

var obj = { key: "value" };
delete obj["key"];

在 JavaScript 中处理对象的非常有用的指南可以在 MDN 上找到。

对于数组,请使用拼接方法:

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. 添加了检查数组中是否存在该元素。如果它不存在,则 reeturn 索引将被-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