如何从 JavaScript 关联数组中删除对象? [英] How do I remove objects from a JavaScript associative array?

查看:33
本文介绍了如何从 JavaScript 关联数组中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个代码:

var myArray = new Object();myArray["firstname"] = "Bob";myArray[姓氏"] =史密斯";myArray[年龄"] = 25;

现在如果我想删除姓氏"?....是否有一些等效的myArray[lastname"].remove()?

(我需要删除元素,因为元素的数量很重要,我想保持干净.)

解决方案

JavaScript 中的对象可以被认为是关联数组,将键(属性)映射到值.

要从 JavaScript 中的对象中删除属性,请使用 delete 运算符:

const o = { lastName: 'foo' }o.hasOwnProperty('lastName')//真删除 o['lastName']o.hasOwnProperty('lastName')//假

请注意,当 delete 应用于 Array,您将创建一个 人口稀少的数组(即缺少索引的数组).

当使用 Array 的实例时,如果您不想创建一个稀疏填充的数组 - 而您通常不想 - 那么您应该使用 Array#spliceArray#pop.>

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

使用 delete 运算符会影响 JavaScript 引擎优化 代码.>

Suppose I have this code:

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

Now if I wanted to remove "lastname"?....is there some equivalent of myArray["lastname"].remove()?

(I need the element gone because the number of elements is important and I want to keep things clean.)

解决方案

Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.

To remove a property from an object in JavaScript you use the delete operator:

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

Note that when delete is applied to an index property of an Array, you will create a sparsely populated array (ie. an array with a missing index).

When working with instances of Array, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice or Array#pop.

Note that the delete operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o, then o will subsequently be garbage collected in the normal way.

Using the delete operator can affect JavaScript engines' ability to optimise code.

这篇关于如何从 JavaScript 关联数组中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆