通过键排序数组或:为什么我的for循环执行的顺序呢? [英] Sort array by key OR: Why is my for loop executing out of order?

查看:95
本文介绍了通过键排序数组或:为什么我的for循环执行的顺序呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要放置在一个特定的顺序,根据一些配置数据对象的数组。我有通过以适当的顺序阵列itterating的问题。我想,如果我做了数组,然后有一个阶梯通过for循环中,我将能够正确执行code。除了在一个用例中,我在其中的第四个项目添加到阵列,然后再回到第三它是伟大的工作。

I have an array of objects which I need placed in a certain order, depending on some configuration data. I am having a problem with itterating through the array in the proper order. I thought that if I made the array, and then stepped through with a for loop, I would be able to execute the code correctly. It is working great except in one use case, in which I add the fourth item to the array and then go back to the third.

links[0] = foo
links[1] = bar
links[2] = foobar
links[3] = a_herring
links[4] = a_shrubery

order = [] //loaded from JSON, works has the numbers 1 2 3 or 4 as values
           //in this case:
order[0] = 1
order[1] = 2
order[2] = 4
order[3] = false
order[4] = 3

for(x in order){        
   if(order[x]){
    printOrder[order[x]]=links[x]
    //remember that in this case order[0] would
}

这应该给我一个数组,看起来像这样:

This should give me an array that looks like this:

//var printOrder[undefined,foo,bar,a_shrubbery,foobar]

但是,当我试图通过数组itterate:

But when I try to itterate through the array:

    for(x in printOrder){
        printOrder[x].link.appendChild(printOrder[x].image)
        printOrder[x].appendChild(printOrder[x].link)
        printOrder[x].appendChild(printOrder[x].text)
        document.getElementById("myDiv").appendChild(printOrder[x]);
    }

我得到富,酒吧,foobar的,a_shrubbery 作为输出来代替。

我需要或者排序这个数组由键值,或者按照正确的顺序通过它一步。

I need to either sort this array by key value, or step through it in the correct order.

推荐答案

阵列实例遍历数字索引的属性应始终以数字指标完成的:

Iterating over the numerically-index properties of Array instances should always be done with a numeric index:

for (var x = 0; x < printOrder.length; ++x) {
  // whatever with printOrder[x]
}

使用了......在声明的形式不会让你predictable排序,正如你所看到的,它可以有其他奇怪的效果太(特别是当你的JavaScript框架或混合工具库或其他)。它用于通过一个对象的属性名称迭代,它不会特殊对待阵列实例。

Using the "for ... in" form of the statement won't get you predictable ordering, as you've seen, and it can have other weird effects too (particularly when you mix in JavaScript frameworks or tool libraries or whatever). It's used for iterating through the property names of an object, and it doesn't treat Array instances specially.

这篇关于通过键排序数组或:为什么我的for循环执行的顺序呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆