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

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

问题描述

如果我有一个来自我收集的 JS 关联数组实际上是一个对象,并且我希望删除一个元素,则使用 delete 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']

所以,总而言之,对对象字面量使用删除.对数组使用拼接.

希望这会有所帮助.

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

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