How to keep the sequence in javascript Map?

后端 未结 2 535
闹比i
闹比i 2021-01-17 17:46

i have myData map as below

 var myData =  new Object();

 myData[10427] = \"Description 10427\";
 myData[10504] = \"Description 10504\";
 myData[10419] = \"D         


        
相关标签:
2条回答
  • 2021-01-17 18:05

    ES6 Maps preserves the insertion order.

    The set method is used for setting the key value pairs

    var myData = new Map();
    myData.set(10427, "Description 10427");
    myData.set(10504, "Description 10504");
    myData.set(10419, "Description 10419");
    

    Map keys and values are printed using

    myData.forEach((value,key) => console.log(key, value));
    

    This will print the keys and values in the insertion order

    0 讨论(0)
  • 2021-01-17 18:19

    Objects are unordered in JS. Use an array if order matters.

    var myData = [];
    myData.push({ "number": 10427, description: "Description 10427" });
    
    0 讨论(0)
提交回复
热议问题