Loop through a 'Hashmap' in JavaScript

后端 未结 8 840
逝去的感伤
逝去的感伤 2020-12-08 09:37

I\'m using this method to make artificial \'hashmaps\' in javascript. All I am aiming for is key|value pairs, the actual run time is not important. The method below works fi

相关标签:
8条回答
  • 2020-12-08 10:09
    for (var i = 0, keys = Object.keys(a_hashmap), ii = keys.length; i < ii; i++) {
      console.log('key : ' + keys[i] + ' val : ' + a_hashmap[keys[i]]);
    }
    
    0 讨论(0)
  • 2020-12-08 10:12

    You can use JQuery function

    $.each( hashMap, function(index,value){
     console.log("Index = " + index + " value = " + value); 
    })
    
    0 讨论(0)
  • 2020-12-08 10:12

    Iterating through a map in vanilla Javacsript is simple .

    var map = {...};//your map defined here
    for(var index in map)
     {
           var mapKey = index;//This is the map's key.
           for(i = 0 ; i < map[mapKey].length ; i++)
            {
                  var mapKeyVal = map[mapKey];//This is the value part for the map's key.
    
    
              }
      }
    
    0 讨论(0)
  • 2020-12-08 10:12

    This is an old post, but one way I can think of is

    const someMap = { a: 1, b: 2, c: 3 };
    Object.keys(someMap)
    .map(key => 'key is ' + key + ' value is ' + someMap[key]);
    

    Should this way of iterating be used? Are there any issues with this approach?

    0 讨论(0)
  • 2020-12-08 10:21

    Do you mean

    for (var i in a_hashmap) { // Or `let` if you're a language pedant :-)
       ...
    }
    

    i is undefined when the for-loop gets set up.

    0 讨论(0)
  • 2020-12-08 10:22

    Hash maps can be tricky, but quite useful. When iterating over one as you would an object, each key is a tuple with [key, value]:

    for (let key of map) {
        console.log('Key is: ' + key[0] + '. Value is: ' + key[1]);
    }
    
    0 讨论(0)
提交回复
热议问题