Ordered hash in JavaScript

前端 未结 9 1012
心在旅途
心在旅途 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:39

    A fairly simple way is to use an array to store the order. You need to write a custom compare function to establish the order you require. The down side is that you have to sort the array and keep track of relations, each time you change the hash table.

    var order=[];
    var hash={"h1":4,"h2":2,"h3":3,"h4":1};
    
    function cmp(a,b) {
      if (hash[a] < hash[b]) return -1;
      if (hash[a] > hash[b]) return 1;
      return 0;
    }
    
    // Add initial hash object to order array
    for(i in hash) order.push(i);
    order.sort(cmp);
    // h4:1 h2:2 h3:3 h1:4
    
    // Add entry
    hash['h5']=2.5;
    order.push('h5');
    order.sort(cmp);
    // h4:1 h2:2 h5:2.5 h3:3 h1:4
    
    // Delete entry
    order.splice(order.indexOf('h5'), 1);
    delete hash['h5'];
    // h4:1 h2:2 h3:3 h1:4
    
    // Display ordered hash array (with keys)
    for(i in order) console.log(order[i],hash[order[i]]);
    

提交回复
热议问题