假设我有这样的代码:

var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

现在如果我想删除“lastname”?....有什么等价物吗 (“姓”)myArray .remove () ?

(我需要元素消失,因为元素的数量很重要,我想保持东西干净。)


当前回答

“数组”:

如果你知道索引:

array.splice(index, 1);

如果你知道这个值:

function removeItem(array, value) {
    var index = array.indexOf(value);
    if (index > -1) {
        array.splice(index, 1);
    }
    return array;
}

得到最多好评的delete答案适用于对象,但不适用于实际数组。如果我使用删除,它从循环中删除元素,但保持元素为空,数组的长度不会改变。在某些情况下,这可能是一个问题。

例如,如果我在删除myArray后对myArray执行myArray. tostring(),它会创建一个空条目,即,。

其他回答

你可以通过显式地将一个条目分配给'undefined'来从你的映射中删除它。就像你的情况:

myArray[“lastname”] = undefined;

这只是删除对象,但它仍然保持数组长度不变。

要从数组中移除元素,你需要做如下操作:

array.splice(index, 1);

我唯一的工作方法是:

function removeItem (array, value) {
    var i = 0;
    while (i < array.length) {
        if(array[i] === value) {
            array.splice(i, 1);
        } else {
            ++i;
        }
    }
    return array;
}

用法:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]

使用splice方法从对象数组中完全移除一个项:

Object.prototype.removeItem = function (key, value) {
    if (value == undefined)
        return;

    for (var i in this) {
        if (this[i][key] == value) {
            this.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");

在Airbnb风格指南(ECMAScript 7)中有一种优雅的方式来做到这一点:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

版权:https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90