简体   繁体   English

在类似数组的对象中添加/删除元素

[英]add/remove elements in array-like object

I have an array-like object: 我有一个类似数组的对象:

[ 1:Array[10], 2: Array[2], 3: Array[2], 4: Array[2], 5: Array[3], 6: Array[1]] [ 1:Array[10], 2: Array[2], 3: Array[2], 4: Array[2], 5: Array[3], 6: Array[1]]

Im trying to remove the first two elements, do some stuff, and then insert them again at the same place. 我试图删除前两个元素,做一些事情,然后在同一位置再次插入它们。

Here is what i do: 这是我的工作:

array = Array.prototype.splice.call(array, 0,2);

When logging array in firefox it show this: 在firefox中记录array ,它显示以下内容:

Array [ <2 empty slots>, Array[1], Array[2], Array[3], Array[1] ]

Looks good to me,I removed the first two elements and the array now starts with 2 empty slots. 对我来说不错,我删除了前两个元素,该数组现在从2个空插槽开始。

So now, what I hope to do is to add objects to these 2 empty slots. 现在,我希望将对象添加到这两个空插槽中。

For simplicity, lets remove to items from the array and then insert them again at the same place: 为了简单起见,让我们从数组中删除项目,然后在同一位置再次插入它们:

var twoFirstItems = Array.prototype.slice.call(array, 0,2);
array = Array.prototype.splice.call(array, 0,2);

Now,to re-insert twoFirstItems I would think that I could do: 现在,要重新插入twoFirstItems我认为我可以这样做:

array.unshift(twoFirstItems)

This does not work as expected, it inserts the array but it does not have a key as it had before its modifikation. 这不能按预期方式工作,它插入了数组,但是没有修改之前的key I assume this has to do with unshift not working the same with an array-like object as with an array . 我认为这与做unshift不与工作的同一array-like object与一个array

So how do you remove/insert elements to an array-like-object properly? 那么,如何正确地将元素删除/插入到array-like-object呢?

If i do the following: 如果我执行以下操作:

  console.log(array);
  console.log(typeof array);

The result: 结果:

Array [ <1 empty slot>, Array[2], Array[2], Array[2], Array[3], Array[1] ]
object

Without any complications, you can just re-assign the modified array at that index. 没有任何复杂性,您只需在该索引处re-assign修改后的数组即可。

 var a = [ [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6] ] a[0] = a[0].map((el) => el * 10) a[1] = a[1].map((el) => el * 20) console.log(a) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM