假设我有这样的代码:

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(),它会创建一个空条目,即,。

其他回答

JavaScript中的对象可以看作是关联数组,将键(属性)映射到值。

要在JavaScript中从对象中删除一个属性,可以使用delete操作符:

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

请注意,当delete应用于数组的索引属性时,您将创建一个稀疏填充的数组(例如。缺少索引的数组)。

当使用Array的实例时,如果您不想创建稀疏填充的数组(通常也不想),那么您应该使用array# splice或array# pop。

请注意,JavaScript中的delete操作符并不直接释放内存。它的目的是从对象中删除属性。当然,如果被删除的属性持有对对象o的唯一剩余引用,那么o随后将以正常方式被垃圾收集。

使用delete操作符会影响JavaScript引擎优化代码的能力。

JavaScript中的所有对象都实现为哈希表/关联数组。因此,以下是等价的:

alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);

并且,如前所述,你可以通过delete关键字从对象中“删除”一个属性,你可以通过两种方式使用它:

delete myObj["SomeProperty"];
delete myObj.SomeProperty;

希望额外的信息能有所帮助…

正如其他答案所指出的,您使用的不是JavaScript数组,而是JavaScript对象,它的工作原理几乎类似于其他语言中的关联数组,只是所有键都被转换为字符串。新的Map以原始类型存储键。

如果你有一个数组而不是一个对象,你可以使用数组的.filter函数,返回一个不删除你想要删除的项的新数组:

var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
    return item !== 'Smith';
});

如果您使用的是较旧的浏览器和jQuery, jQuery有一个$。Grep方法,工作原理类似:

myArray = $.grep(myArray, function(item) {
    return item !== 'Smith';
});

在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

您正在使用Object,并且您一开始没有关联数组。使用关联数组,添加和删除项如下所示:

    Array.prototype.contains = function(obj)
    {
        var i = this.length;
        while (i--)
        {
            if (this[i] === obj)
            {
                return true;
            }
        }
        return false;
    }


    Array.prototype.add = function(key, value)
    {
        if(this.contains(key))
            this[key] = value;
        else
        {
            this.push(key);
            this[key] = value;
        }
    }


    Array.prototype.remove = function(key)
    {
        for(var i = 0; i < this.length; ++i)
        {
            if(this[i] == key)
            {
                this.splice(i, 1);
                return;
            }
        }
    }



    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }

        return vars;
    }


    function ForwardAndHideVariables() {
        var dictParameters = getUrlVars();

        dictParameters.add("mno", "pqr");
        dictParameters.add("mno", "stfu");

        dictParameters.remove("mno");


        for(var i = 0; i < dictParameters.length; i++)
        {
            var key = dictParameters[i];
            var value = dictParameters[key];
            alert(key + "=" + value);
        }
        // And now forward with HTTP-POST
        aa_post_to_url("Default.aspx", dictParameters);
    }


    function aa_post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        // Move the submit function to another variable
        // so that it doesn't get written over if a parameter name is 'submit'
        form._submit_function_ = form.submit;

        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var i = 0; i < params.length; i++)
        {
            var key = params[i];

            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form._submit_function_(); // Call the renamed function
    }