Maintaining array order in Javascript

后端 未结 3 1634
清酒与你
清酒与你 2021-01-29 14:33

I am new to JavaScript and I am having trouble working with my array, I want my array ordered how I explicitly write it and not how JavaScript decides it wants it.

If we

3条回答
  •  伪装坚强ぢ
    2021-01-29 14:41

    You're using an object {}, not an array []. Objects have no explicit order, where Arrays do. That's why you're having your problem. Change your {} to [] and you'll be fine. You could even use an array of objects.

    var array = [
        {0: 'zero'}, 
        {4: 'four'}, 
        {2: 'two'}
    ];
    

    Looping over that like so

    for(var i = 0; i < array.length; i++){
      console.log(array[i]);
    }
    

    Gives us our normal order.

    Object {0: "zero"}
    Object {4: "four"}
    Object {2: "two"} 
    

    Another Edit: The problem is you're trying to have an array that has properties and values just like an object, without using an object, {property: value} - that can't really be done with an array. To loop over an array like you want, it's as simple as

    var arr = [1,2,3]
    

    and

    for(var i = 0; i < arr.length; i++){
      console.log(i) //1,2,3
    }
    

    but the problem, like mentioned above, is you want more complex arrays which you simply can't do.

提交回复
热议问题