javascript – 我应该如何以索引顺序迭代稀疏数组?

前端之家收集整理的这篇文章主要介绍了javascript – 我应该如何以索引顺序迭代稀疏数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个稀疏数组,其内容不保证以索引顺序插入,但需要按索引顺序迭代.要遍历稀疏数组,我了解您需要使用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页面上提供的填充程序:

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

猜你在找的JavaScript相关文章