gpt4 book ai didi

javascript - 为什么 JavaScript 对我的对象重新排序?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:05 26 4
gpt4 key购买 nike

出于某种原因,这个函数:

function returnDoubled (numArray) {
var newObj = {};
for (var i = 0; i < numArray.length; i++) {
newObj[numArray[i]] = numArray[i] * 2;
}
return(newObj);
}

console.log(returnDoubled([0, 17, 3, 1, -1, 12, 7]));

在我的控制台中返回以下内容:

Object {0: 0, 1: 2, 3: 6, 7: 14, 12: 24, 17: 34, -1: -2} 

我觉得很奇怪。为什么 JavaScript 选择按此顺序排列 newObj 对象,而不是我在最初传递给它的数组中指定的顺序?

谢谢!

最佳答案

JavaScript 中对象的属性没有定义的顺序。引擎可以自由地以任何它喜欢的方式对其进行排序,不同的引擎在这方面可能会有不同的表现。有关此行为的详细信息,请参阅此 MDN article :

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype)…

So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

如果您需要以特定顺序排列元素,我建议重构您的代码以改为使用数组。

关于javascript - 为什么 JavaScript 对我的对象重新排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com