简体   繁体   English

map integer 到 Javascript 中其他变量的正确方法是什么

[英]What is proper way to map integer to other variable in Javascript

I would like to link integer => something in JavaScript without need of iterating over each element of array.我想链接integer => something JavaScript 中的某些内容,而无需遍历数组的每个元素。 In PHP for example I can use arbitrary values without making array bigger.例如,在 PHP 中,我可以使用任意值而不会使数组变大。

Let's say my test JS code would be假设我的测试 JS 代码是

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

Given this example code, that array contains many empty elements, which implies it's not correct way to do this.鉴于此示例代码,该数组包含许多空元素,这意味着这样做是不正确的方法。 I could in theory do array of objects where {int:1,val:'hello'} but this would require me to iterate over said array to access one of elements, which is not what I need.理论上我可以做对象数组,其中{int:1,val:'hello'}但这需要我遍历所述数组以访问其中一个元素,这不是我需要的。

Is there better way to do this in JavaScript?在 JavaScript 中有更好的方法吗? If not, how bad is that method, like what's the amount of wasted memory for this?如果不是,那么该方法有多糟糕,比如为此浪费了多少 memory?

Change experiment = [] to experiment = {} .experiment = []更改为experiment = {}

You want use an object instead of array.您想要使用 object 而不是数组。 You need not iterate over all keys to find the value.您无需遍历所有键来查找值。 For example experiment[1000] will find the value "world" in constant time O(1) complexity.例如experiment[1000]将以恒定时间O(1)复杂度找到值"world"

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM