1

I am going through the process of creating a bunch of array's , adding elements with push() and getting back a few arrays with a bunch of elements based on the process used to get the elements on the ui.

So i end up with something like this.

[Object, Object, Object]
0: Object
  parcels: Array[1]
  ref: "IDE25.8.2013.0637548291"
  region: "remote"
  service: "Early Delivery"
  totalPrice: 210
  weight: "1"

1: Object
  parcels: Array[1]
  ref: "IDE25.8.2013.1507892643"
  region: "remote"
  service: "Saturday"
  totalPrice: 135.67
  weight: "1"

2: Object
  parcels: Array[1]
  ref: "IDE25.8.2013.1507432643"
  region: "remote"
  service: "Saturday"
  totalPrice: 115.67
  weight: "1"

From what i have learnt in order to "remove" one of the objects you need to add a delete

So i use

delete consignmentsArr[1];

Now i would assume that the delete would delete the array , but it does not. One is left with what is called a sparse array. So the array does not exist in that is cannot be used, in that it's elements and the objects are not defined but it still exists in the index of the group of arrays as an

[Object, undefined × 1, Object]

This however destroys the logic that has been created with the ui elements that display the elements in the other arrays.

I am not really trying to find out how to fix this problem in my application. What i want to know its why is this the default behavior in javascript? Why would a delete not just be a delete as the name implies, and then reorder the index based on the objects that still exist? Why would leaving it as a sparse array be of any benefit in the development process? Also ... why not rename to

sparse consignmentsArr[1];
4

4 回答 4

1

我认为,delete运算符并不意味着删除数组中的项目,它只是意味着从您给定的索引中取消链接对象。

想想consignmentsArr是一个容器,里面有三个盒子。
每个盒子里都有一个苹果。
delete consignmentsArr[1]意思是把苹果从第二个盒子里拿走。
你认为之前的第三个盒子,现在是第二个盒子吗?^_^

于 2013-09-25T12:48:57.207 回答
1

以下是对 Javascriptdelete运算符(用于数组)的可能解释:

对于 Javascript 数组,delete操作是O(1),因为它只是将随机访问数组的值更改undefined

像这样重新组织数组索引的操作(在伪javascript中):

a = [1,2,3]-> delete a[1]-> a 现在是[1,3]

将是O(N)因为在最坏的情况下,您将删除第一个元素,并且必须移动数组的其余部分。

请参阅http://en.wikipedia.org/wiki/Array_data_structure并阅读标题Efficiency下的部分。

补充:delete对数组运算符 行为的另一种解释是,数组上的运算符与其他对象上的运算符delete执行相同的操作。delete

如果我有一个给定的对象:然后a = {'hi': 'hello', 'bye': 'good bye'}我变成.delete a['hi']a['hi']undefined

如果我有一个数组arry = [1,2,3],那么delete arry[1]那么arry[1]也变为undefined.

于 2013-09-25T12:38:07.090 回答
1

我认为您的意思是使用拼接方法。

consignmentsArr.splice(1, 1);

Delete用于从对象中删除属性。

于 2013-09-25T12:33:55.407 回答
0

删除操作符从对象中删除一个属性。

您可以使用以下任何一种

delete object.property
delete object['property']

delete不是数组上的运算符。这就是为什么重新排序索引不适用于delete.

您仍然可以使用 splice 从数组中完全删除一个项目并重新排序索引。

arr.splice(1, 1);
于 2013-09-25T12:41:43.687 回答