javascript 如何在javascript Map中保持序列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17696473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:14:53  来源:igfitidea点击:

How to keep the sequence in javascript Map?

javascriptarrayssorting

提问by emilly

i have myData map as below

我有如下 myData 地图

 var myData =  new Object();

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

but now when i iterate over myData, i don't get same sequnce in chrome and IE works fine in firefox. It iterates in ascending order of key

但是现在当我遍历 myData 时,我在 chrome 中没有得到相同的序列,而 IE 在 Firefox 中工作正常。它以键的升序迭代

for (var key in myData) {
  alert("key is"+key);
  }

i get the output in ascending order in alert as 10419,10427,10504

我在警报中按升序得到输出 10419,10427,10504

How i can make sure to iterate in same order as data as inserted in map?

我如何确保以与插入到地图中的数据相同的顺序进行迭代?

回答by Mamtha Soni K

ES6 Maps preserves the insertion order.

ES6 Maps 保留插入顺序。

The set method is used for setting the key value pairs

set方法用于设置键值对

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

这将打印插入顺序中的键和值

回答by Quentin

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

JS 中的对象是无序的。如果顺序很重要,请使用数组。

var myData = [];
myData.push({ "number": 10427, description: "Description 10427" });