gpt4 book ai didi

javascript - 将 2 个数字组合起来用作对象的键的有效方法是什么?

转载 作者:行者123 更新时间:2023-12-02 16:45:08 25 4
gpt4 key购买 nike

我使用以下模式来索引从数字对到数字的注入(inject):

var myHash = {};
...
for (... billion of iterations ...)
var x = someNum;
var y = otherNum;
myHash[x + "," + y] = z;

此代码的问题是我使用字符串作为 myHash 的键,经测试它比整数键慢得多。我的问题是:在将两个数字用作对象的键之前,有什么更智能的方法来组合它们?即,如何将 2 个 double 组合成一个唯一的整数?

最佳答案

JavaScript中有数组的定义:

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232 - 1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 232. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

换句话说,如果您指定的索引是表示 0 到 0xFFFFFFFE 之间的整数的数字,则将其用作数组索引。任何其他值都被视为字符串,并用于创建对象成员而不是数组项。

因此,如果您的索引有适合有效范围(0 到 0xFFFFFFFE)的约束,那么您就可以了。否则,你所拥有的可能是最快的。

因此以下表示字符串索引,它们是对象 myHash 的成员:

myHash[x + "," + y] = z;

有人提到使用数组的数组。那对你没有帮助。你会得到很多数组而不是很多字符串。如果不是更慢的话,可能也差不多。这个想法是这样的:

myHash[x] = [];  // initialize the sub-array (must be done only once per value of 'x'
myHash[x][y] = z; // save z in that array

我不推荐使用双数组,因为它会为 myHash 之上的每个“x”值初始化一个数组,并且这可能不会比字符串连接快(特别是因为您必须测试 myHash 是否[x] 数组是否已定义...)。

所以...可以写:

myHash[3.3] = "that worked?";

但是如果之后您检查长度,您会发现它为零:

console.log("Hash length = " + myHash.length);

这是因为 3.3 不是整数。

关于javascript - 将 2 个数字组合起来用作对象的键的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27162003/

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