-1

我想integer => something在 JavaScript 中链接而不需要遍历数组的每个元素。例如,在 PHP 中,我可以使用任意值而不会使数组变大。

假设我的测试 JS 代码是

let experiment = [];
experiment[1] = "hello";
experiment[1000] = "world";
console.log(experiment);

鉴于此示例代码,该数组包含许多空元素,这意味着执行此操作的方法不正确。理论上我可以在其中做对象数组,{int:1,val:'hello'}但这需要我遍历所述数组以访问其中一个元素,这不是我需要的。

有没有更好的方法在 JavaScript 中做到这一点?如果不是,那么该方法有多糟糕,例如为此浪费了多少内存?

4

2 回答 2

2

更改experiment = []experiment = {}

于 2020-08-21T08:40:44.403 回答
2

您想使用对象而不是数组。您无需遍历所有键来查找值。例如experiment[1000],将找到"world"恒定时间O(1)复杂度的值。

let experiment = {};
experiment[1] = "hello";
experiment[1000] = "world";
console.log(experiment);
console.log(experiment[1]);
console.log(experiment[1000]);

于 2020-08-21T08:48:51.300 回答