Javascript 在 jquery 中,如何通过 index["key"] 或 value 删除数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11170825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:44:39  来源:igfitidea点击:

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

javascriptjquery

提问by Randel Ramirez

In jQuery/JavaScript, How do I remove an array element?

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

something like:

就像是:

array.remove(array["key"]);

// or 

array.remove("value")

回答by gion_13

For arraysuse the splicemethod :

对于数组,使用splice方法:

var array = [1, 2, 3, 4, 5];
array.splice(2, 1);
console.log(array); // [1, 2, 4, 5]

You could make your own function to remove (the first occurrence of) a certain element in the array :

您可以创建自己的函数来删除(第一次出现)数组中的某个元素:

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]

If you want to remove an item from an object, use the deletesyntax :

如果要从对象中删除项目,请使用以下delete语法:

var a = {key1: 'val1', key2: 'val2'};
delete a.key1;
console.log(a); // {key2: 'val2'}

And yet again you can make your own function to handle this :

再一次,您可以创建自己的函数来处理此问题:

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'}

Update:

更新

  1. Although this was just an example, as @Eric pointed out, it's not a very good idea to modify an object's prototype. So I've re-written examples that do not alter the object's state
  2. Added a check if the element exists in the array. If it doesn't exist, the reeturned index would be -1and the splice method would remove the last element (the first element from the end of the array). Thanks, @amnotiam!
  1. 尽管这只是一个例子,正如@Eric 指出的那样,修改对象的原型并不是一个好主意。所以我重写了不改变对象状态的例子
  2. 添加了元素是否存在于数组中的检查。如果它不存在,则返回的索引将是-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;
};

And of course, since the question was tagged jquery, we can add this function as a jquery plugin :

当然,由于问题被标记为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); 

And then use it like this :

然后像这样使用它:

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}

回答by Andrew Whitaker

Judging by your code, it sounds like you want to delete an object's property, which you would do with delete:

从你的代码来看,听起来你想删除一个对象的属性,你可以这样做delete

var obj = { key: "value" };

delete obj["key"];

A very useful guide on working with objects in JavaScript can be found on MDN.

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

回答by slash197

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1);

will remove 1 item from array fruits, position 2, which is Apple

将从数组水果中删除 1 个项目,位置 2,即 Apple

回答by Nicola Peluchetti

array["key"]is not the key of an array (there are no associative arrays in javascript, if you come from PHP they might look like them, but they are objects) but the property of an object, i think you can use delete

array["key"]不是数组的键(javascript 中没有关联数组,如果您来自 PHP,它们可能看起来像它们,但它们是对象)而是对象的属性,我认为您可以使用 delete

delete array.key