簡體   English   中英

map integer 到 Javascript 中其他變量的正確方法是什么

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM