![](/img/trans.png)
[英]Javascript/jQuery variable, what is the proper way to use a var?
[英]What is proper way to map integer to other variable in Javascript
我想鏈接integer => something
JavaScript 中的某些內容,而無需遍歷數組的每個元素。 例如,在 PHP 中,我可以使用任意值而不會使數組變大。
假設我的測試 JS 代碼是
let experiment = [];
experiment[1] = "hello";
experiment[1000] = "world";
console.log(experiment);
鑒於此示例代碼,該數組包含許多空元素,這意味着這樣做是不正確的方法。 理論上我可以做對象數組,其中{int:1,val:'hello'}
但這需要我遍歷所述數組以訪問其中一個元素,這不是我需要的。
在 JavaScript 中有更好的方法嗎? 如果不是,那么該方法有多糟糕,比如為此浪費了多少 memory?
將experiment = []
更改為experiment = {}
。
您想要使用 object 而不是數組。 您無需遍歷所有鍵來查找值。 例如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.