简体   繁体   中英

Javascript: iterate through dynamically changing dictionary

I'm trying to iterate through a dictionary while dynamically changing its size, by adding elements in Javascript. The dictionary is initialized with 1 element. Pseudo code should look like this:

dict = {1:1};
i = 0;
for key in dict{
  dict[i] = i+1;
  i++;
  if i==10{break;}
}

Dictionary keys (object properties) shouldn't be integers, but this will grow your "dictionary" to have 10 elements (it will only add nine because it will skip when i == 1 :

var dict = { 1: 1 };
for (var i = 0; i < 10; i++) {
    if (!dict.hasOwnProperty(i)) {
        dict[i] = i + 1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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