在Javascript维护阵列秩序 [英] Maintaining array order in Javascript
问题描述
我是新来的JavaScript,我有麻烦我的数组的工作,我想我的数组排序我如何明确写入它,而不是如何JavaScript的决定需要它。
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.
如果我们有一个阵列
var array = {
0: 'zero',
4: 'four',
2: 'two'
};
当我选择在控制台中显示此,或迭代它,它的重新排序像这样
When I choose to display this in the console, or iterate over it, Its reordered like this
array = {
0: 'zero',
2: 'two',
4: 'four'
};
我已经试过2个循环,到目前为止,for循环,也是在语句的循环。
根据双方的工作,我如何假定他们会因为它们使用一个键和在那里工作的方式上/下,为了使我指定的是绝对没有用的。
I have tried 2 loops so far, The for loop, and also the for loop with the in statement. Both work according how I assumed they would as they use a key and work there way up/down, making order I specify is absolutely useless.
我怎么能写/打印/工作与我的数组作为其排序,在其他语言如PHP的那样简单。
How can I write/print/work with my array as its ordered, In other languages such as PHP its as simple as
$array = array(
0 => 'zero',
4 => 'four',
2 => 'two'
);
foreach($array as $key => $value)
echo $key ."\n";
这将输出
0
4
2
先谢谢了。
推荐答案
您正在使用对象 {}
,而不是一个数组 []
。对象没有明确的顺序,其中阵列做。这就是为什么你遇到你的问题。更改 {}
到 []
,你会没事的。你甚至可以使用对象的数组。
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'}
];
在循环,像这样
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 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]
和
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.
这篇关于在Javascript维护阵列秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!