Ordered hash in JavaScript

前端 未结 9 1003
心在旅途
心在旅途 2020-12-05 17:34

JavaScript objects have no order stored for properties (according to the spec). Firefox seems to preserve the order of definition of properties when using a for...in<

9条回答
  •  天命终不由人
    2020-12-05 17:47

    JavaScript in 2016, specifically EcmaScript 6, supports the Map built-in class.

    A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.

    That's what you need. (I wonder why that is the first info in the description of this data structure, though.)

    For example,

    m = new Map()
    
    m.set(3,'three')
    m.set(1,'one')
    m.set(2,'two')
    
    m // Map { 3 => 'three', 1 => 'one', 2 => 'two' }
    
    [...m.keys()] // [ 3, 1, 2 ]
    

    or the example from the docs:

    var myMap = new Map();
    myMap.set(0, 'zero');
    myMap.set(1, 'one');
    
    myMap // Map { 0 => 'zero', 1 => 'one' }
    
    for (var [key, value] of myMap) {
      console.log(key + " = " + value);
    }
    
    for (var key of myMap.keys()) {
      console.log(key);
    }
    
    for (var value of myMap.values()) {
      console.log(value);
    }
    
    for (var [key, value] of myMap.entries()) {
      console.log(key + " = " + value);
    }
    

提交回复
热议问题