但是,根据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>"); }
所有人似乎都尊重索引顺序,所以我始终相信这一点吗?否则,我如何以索引顺序最好地获取它们?
解决方法
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)); } }