在关联数组上删除vs splice [英] Delete vs splice on associative array

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

问题描述

如果我有一个JS关联数组,它来自我收集的实际上是一个对象,我希望删除一个元素,使用删除myArr [someId] 将设置未定义的元素,而splice根本不起作用...如果我想删除一个元素(而不是将其设置为 undefined

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)

推荐答案

js中的术语起初可能会令人困惑,所以让我们理顺它。

The terminology in js can be confusing at first, so lets straighten that out.

是的,几乎js中的所有东西都是一个对象。但是,数据类型存在差异。

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 it's different than an object literal.

var x = []; //array
var y = {}; //object literal

数组就像一个列表。数组的键可以是数字索引或字符串。

An array is like a list. The keys of an array can be a numerical index or a string.

var x = ['a','b']; // x[0] === 'a', x[1] === 'b';
var x = [];
    x['one'] = 'a';
    x['blah'] = 'b'; 

对象文字就像字典。它们可以以类似的方式使用。

Object literals are like dictionaries. They can be used in a similar way.

var x = { 0: 'a', 1: 'b' };
var x = { one: 'a', two: 'b' };

但是,您需要了解差异。

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.

数组具有自动长度属性,该属性根据数组中元素的总数自动递增和递减。你没有得到对象文字。数组也可以获得所有其他特定于数组的方法,如shift,unshift,splice,pop,push等。对象文字没有这些方法。

Arrays have the automated "length" property, that 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.

让我们谈谈关于删除以及在数组和对象文字上发生的事情。

Let's talk about delete and what happens on an array and on an object literal.

var x = ['a', 'b']; //["a", "b"]
delete x[0]; //[undefined, "b"]

var x = {0:'1', 1:'b'}// { 0:"1", 1:"b"}
delete x[0]; // { 1:"b" }

如果对数组元素执行删除,数组的长度不会改变。元素索引被保留,值设置为'undefined';

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.

var x = ['a', 'b']; 
x.splice(0,1); //modifies x. ['b']

因此,总结一下,在对象文字上使用delete。在数组上使用拼接。

希望这有帮助。

这篇关于在关联数组上删除vs splice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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