关联数组上的删除与拼接
如果我有一个 JS 关联数组,它来自我收集的实际上是一个对象,并且我希望删除一个元素,使用 delete myArr[someId]
会将元素设置为未定义,而 splice 不会根本不起作用...那么,如果我想删除一个元素(而不是将其设置为未定义
),那么关联数组的替代方案是什么
If I have a JS associative array which is from what I gather is really an object, and I wish to remove an element, using delete myArr[someId]
will set the element to undefined, whilst splice won't work at all... so what is the alternative for an associative array if I wish to delete an element (rather than setting it to undefined
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
js 中的术语一开始可能会令人困惑,所以让我们先理清一下。
是的,js 中几乎所有东西都是对象。但是,数据类型存在差异。
数组可以像关联数组一样使用,但它与对象文字不同。
数组就像一个列表。数组的键可以是数字索引或字符串。
对象字面量就像字典。它们可以以类似的方式使用。
然而,这是您需要了解差异的地方。
您可以像使用对象文字一样使用数组,但不能像使用数组一样使用对象文字。
数组具有自动的“长度”属性,它会根据数组中元素的总数自动递增和递减。你无法通过对象字面量得到这个。数组还获得所有其他特定于数组的方法,如 shift、unshift、splice、pop、push 等。对象字面量没有这些方法。
让我们谈谈删除以及数组和对象字面量上发生的情况。
如果对数组的元素执行删除,数组的长度不会改变。元素索引被保留,值被设置为'undefined';
相反,对对象文字执行删除将从对象中删除键/值。
最后,如果你想从数组中删除一个元素。
因此,总而言之,对对象文字使用删除。在数组上使用拼接。
希望这有帮助。
The terminology in js can be confusing at first, so lets straighten that out first.
Yes, pretty much everything in js is an object. However, there are differences in the data types.
An array can be used like as associative array, but its different than an object literal.
An array is like a list. The keys of an array can be a numerical index or a string.
Object literals are like dictionaries. They can be used in a similar way.
However, this is where you need to understand the differences.
You can use an array like an object literal, but you can't use an object literal quite like an array.
Arrays have the automated "length" property, This increments and decrements automatically based on the total number of elements in the array. You don't get this with object literals. Arrays also get all of the other array-specific methods like shift, unshift, splice, pop, push, etc. Object literals don't have those methods.
Lets talk about delete and what happens on an array and on an object literal.
If you perform a delete on an element of an array, the length of the array doesn't change. The element index is preserved and the value is set to 'undefined';
Conversely, performing a delete on an object literal removes the key/value from the object.
Finally, if you want to remove an element from an array.
So, in summary use delete on object literals. Use splice on arrays.
Hope this helps.
没有其他选择。
myArr["someCrazyIndexYouHaventPreviouslyUsed"]
将返回未定义;对于不存在的索引,关联数组总是会给出undefined
。因此,删除
myArr[someId]
将导致myArr
将someId
视为不存在的所有其他索引 - 这不是您想要的?There is no other option.
myArr["someCrazyIndexYouHaventPreviouslyUsed"]
will return undefined; an associative array will always give youundefined
for indexes that don't exist.So delete
myArr[someId]
will causemyArr
to treatsomeId
like every other index that doesn't exist—isn't that what you want?