gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:32:14 24 4
gpt4 key购买 nike

我有一个稀疏数组,其内容不能保证按索引顺序插入,但需要按索引顺序迭代。要遍历稀疏数组,我知道您需要使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com