javascript - 我应该如何按索引顺序遍历稀疏数组?

标签 javascript arrays sparse-array

我有一个稀疏数组,其内容不能保证按索引顺序插入,但需要按索引顺序迭代。要遍历稀疏数组,我知道您需要使用 for..in 语句。

然而,根据this article :

There is no guarantee that for...in will return the indexes in any particular order

但是stackoverflow questions like this建议虽然不能保证对象属性顺序,但数组顺序是:

properties order in objects are not guaranted in JavaScript, you need to use an Array.

tested this在最新版本的 Chrome、Firefox 和 IE 中。

<ol id="items"></ol>
var list = [];

function addItem(index) {
    list[index] = { idx : index };
}

var insertOrder = [ 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 ];

for ( var i = 0; i < 15; i++ ) {
    addItem(insertOrder[i]);
}

for(var item in list) {
    $("#items").append("<li>" + list[item].idx + "</li>");
}

所有似乎都遵守索引顺序,所以我可以相信情况总是如此吗?否则,我如何最好地按索引顺序获取它们?

最佳答案

MDN有你原来问题的答案:

Note: for..in should not be used to iterate over an Array where index order is important.

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

您不必使用for..in 来遍历稀疏数组,您应该definitely avoid doing so如果可以的话。

你可以只使用.forEach:

list.forEach(function (el) {  // add a second parameter if you need the indices
    $("#items").append($("<li>").text(el.idx));
});

forEach is defined按索引顺序迭代并仅包含数组中存在的元素:

forEach executes the provided callback once for each element present in the array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined.


如果您的目标环境不支持 forEach,您可以使用以下内容,或该 MDN 页面上提供的 shim:

for (var i = 0; i < list.length; i += 1) {
    if (i in list) {
        $("#items").append($("<li>").text(list[i].idx));
    }
}

关于javascript - 我应该如何按索引顺序遍历稀疏数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27598340/

相关文章:

javascript - Jest 在箭头函数中具有空名称属性

javascript - 如何在 javascript 中几秒钟后向用户显示错误消息后隐藏/删除错误消息

javascript - 分解 PHP/Typescript 数组的第 2 层元素

javascript - Node.js 中稀疏数组的内存消耗

javascript - 尝试访问函数构造函数内部的变量时出现引用错误

javascript - 将 y 轴显示为百分比?

c++ - 删除 C++ 中的每个指针作为指向数组的指针是否安全?

c++ - 相邻数组元素的地址之间的差异..?

arrays - 在matlab中设置稀疏矩阵的最快方法

Matlab:每行或列的第一个非零元素