Javascript数组拼接移除数据但不重置索引

Javascript Array splice removes data but does not reset index

我有一组对象。 它有 3 个对象

然后我用 arr.splice(0,1) 我重复了 3 次。 然后我将一个新对象添加到(应该是一个空数组) 并在控制台中打印出整个数组。

如您所见,它是数组中唯一的对象,但不是从索引 0 开始,而是从索引 3 开始。 此外,0、1、2 的索引不存在,它们不是 "null" 或类似的东西。他们走了。 怎么回事?

这是要删除的实际代码。我调用它 3 次。

this.removeSelected = function () {

        //Remove from array
        //I have verified that selFramePos=0 many times. 
        f.splice(selFramePos, 1);
}

我在每个数组槽中保留的这个对象(只是一堆数据,没什么特别的):

  Data = {
        normal : normData,
        imageUrl: selfDefaults.viewport.src,
        topLeftX: norm(cf.paper.width, vpo.cx, vpw),
        topLeftY: norm(cf.paper.width, vpo.cy, vpw),
        width: norm(cf.paper.width, vpo.width, vpw),
        height: norm(cf.paper.width, vpo.height, vpw),
        rotation: selfRotator.getRotation().rotation,
        cropping:
        {
            shape: selfSelector.getSelection().shape,
            tlx: mathUtils.normalize(cf.paper.width, selfSelector.getSelection().left, vpw),
            tly: mathUtils.normalize(cf.paper.width, selfSelector.getSelection().top, vpw),
            w: mathUtils.normalize(cf.paper.width, selfSelector.getSelection().width, vpw),
            h: mathUtils.normalize(cf.paper.width, selfSelector.getSelection().height, vpw),
            color: selfSelector.getSelection().color,
            opacity: selfSelector.getSelection().opacity
        },
        filters: null,
        transition:
{
    type: 'dissolve',
    time: 500
},
        requireUserInput: true
    }

我的问题是我一直在创建索引号不断增加的新数组槽,如下所示:

        var i=0
        function add2Array () {
        arr[i]='something'
        i++
        }

因此,每次我调用该函数时,它都会创建一个 'unique id' 排序,而不是使用索引和位置。

我通过删除 i 并只使用 'push' 而不是任意增加索引来修复它。

JavaScript 没有大多数其他语言中实现数组的方式。

文档状态:

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.

ar[i] 表示法仅指对象 ar 的 属性 i,可以是数字。

以下在JavaScript中是完全合法的:

var ar={};
ar[1] = 1;
ar[3] = 2;

我们仍然称之为 array。但它不必具有连续的索引。需要注意的是,这样的数组length属性将是3(其index).

因此,将 JS 数组视为具有数字属性的特殊对象(请参阅上面文档中的引用)的最合乎逻辑的方式。

then I added a new object to the (what is supposed to be an empty) array

但似乎没有包含它的新长度。使用 push 添加项目,这将自动完成。