简体   繁体   English

具有整数键的稀疏Javascript数组是否仍按键排序?

[英]Does a sparse Javascript array with whole number keys remain sorted by key?

For example: 例如:

var a = [];
a[5] = 'five';
a[2] = 'two';
a[11] = 'eleven';
a[210] = 'two-ten';
a[4] = 'four';
a[56] = 'fifty-six';
a[1] = 'one';
a[39] = 'thirty-nine';

for( var i in a ) {
    if( a.hasOwnProperty(i) ) {
        console.log(i+":"+a[i]);
    }
}

Results in the following (for a few browsers I have handy to test.) 结果如下(对于一些我方便测试的浏览器。)

1:one
2:two
4:four
5:five
11:eleven
39:thirty-nine
56:fifty-six
210:two-ten

Is this standard, reliable behaviour? 这是标准的,可靠的行为吗?

They will always be in order, yes, but standards (as far as I'm aware) end up setting all of the in-between indexes as undefined. 它们总是按顺序排列,是的,但标准(据我所知)最终将所有中间索引设置为未定义。

Edit: If you initialize it as an object, with curly braces, instead of square braces (for arrays) you may get irregular behaviors between browsers. 编辑:如果您将其初始化为对象,使用花括号,而不是方括号(对于数组),您可能会在浏览器之间获得不规则的行为。

ECMA-262 does not specify enumeration order. ECMA-262未指定枚举顺序。

Some browser implement them in ordered way others don't, like V8 to save memory. 有些浏览器以有序的方式实现它们,有些则不像V8那样节省内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 键未使用 javascript 在 JSON 数组中排序 - key is not sorted in JSON array using javascript Javascript-将JavaScript对象数组转换为排序的键/值javascript对象 - Javascript - transform array of javascript objects into a sorted key/value javascript object 如果多个键具有相同的值,则按值排序 JavaScript Object 然后键(按字母顺序)。 按顺序返回排序的键 - Sort JavaScript Object by value and then key(alphabetically) if multiple keys has same value. Return sorted keys in order Javascript稀疏数组兼容性 - Javascript sparse array compatability 在 Javascript 中压缩稀疏数组? - Condensing a sparse array in Javascript? 为什么for-of不能跳过稀疏数组的空插槽? [JavaScript的] - Why does for-of not skip empty slots of a sparse Array? [JavaScript] 如果数组更改但某些键保持不变,React 是否会重新渲染 FOR 循环的所有组件? - Does React rerender all the components of a FOR loop if the array changes but some of the keys remain the same? 根据键数组 javascript 重新排列 object 键 - Rearrange object key based on array of keys javascript 使用排序数组对对象键进行排序 - Sort object keys with a sorted array 按键数对对象数组进行排序(JavaScript) - Sort Array Of Objects By Number of Keys (JavaScript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM