This answer表示迭代稀疏数组的最佳方法是使用 for X in Array
但是,当我尝试这个时,我绊倒了,因为 X
的类型是一个字符串,而不是我期望的整数索引。 (一切都很好,直到我将它添加到另一个整数......)
var arr = [];
arr[10000] = "Hello";
var shifted = []
for (var x in arr)
shifted[10+x] = arr[x];
“预期”:
shifted[10010] = "Hello
实际
shifted["1010000"] = "Hello"
是否有更好的方法使用索引迭代稀疏数组,或者我应该使用 Number(X)
哪里需要?
最佳答案
这就是 V8(和其他 JavaScript 引擎)处理数组的方式:
V8 uses two different methods to handle arrays:
Fast elements:
Designed for arrays where set of keys are very compact. They have a linear storage buffer that can be accessed very efficiently.Dictionary elements:
Designed for sparse arrays which don’t have every elements inside of them. It is actually a hash table, more expensive to access than “Fast Elements”Source: http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/
当您使用稀疏数组时,键将转换为字符串,然后进行哈希处理。如果您想要数字键:不要使用稀疏数组或手动将键转换为数字。
关于javascript - 迭代稀疏数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20326823/