JavaScript:类映射数组、排序和添加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16473854/
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 04:50:10  来源:igfitidea点击:

JavaScript: Map-Like Array, Sorting and Adding

javascriptarraysmap

提问by felix_xiao

I'm trying to create a map or dictionary style data structure in JavaScript. Each string key points to an array of int, and I'd like to do a few simple things with the arrays that the keys point to.

我正在尝试在 JavaScript 中创建地图或字典样式的数据结构。每个字符串键都指向一个 int 数组,我想对键指向的数组做一些简单的事情。

I have a bunch of animals, each with an ID (1,2,3,...). I want to put these in a map so I know that 1,4,5 are cats and that 2,3,6 are dogs.

我有一堆动物,每个动物都有一个 ID(1,2,3,...)。我想把这些放在地图上,所以我知道 1,4,5 是猫,2,3,6 是狗。

Here's what I have for code to explain it better.

这是我可以更好地解释它的代码。

var myMap = {};
myMap["cats"] = new Array(1,4,5);   //animals 1,4,5 are cats
myMap["dogs"] = new Array(2,3,6);   //animals 2,3,6 are dogs  

1) How would I add something to an array? For example, if animal #7 is a cat, would the following code be correct?

1)如何向数组中添加内容?例如,如果动物 #7 是一只猫,那么下面的代码是否正确?

myMap["cats"].push(7);   //so that myMap["cats"] is now an array with [1,4,5,7]

2) How would I sort the map so that the keys are ordered by the number of items in their arrays? In this case, myMap["cats"] would be in front of myMap["dogs"] because the array for "cats" has more items than the array for "dogs". Would the following code be correct?

2)我将如何对地图进行排序,以便键按数组中的项目数排序?在这种情况下,myMap["cats"] 将在 myMap["dogs"] 前面,因为“cats”的数组比“dogs”的数组有更多的项目。以下代码是否正确?

myMap.sort(function(a,b){return myMap[b].length - myMap[a].length});

If there's a much more efficient way to do this in JavaScript, please let me know. Thank you so much!

如果在 JavaScript 中有更有效的方法可以做到这一点,请告诉我。太感谢了!

回答by

Seems you've answered your own first question.

似乎您已经回答了自己的第一个问题。



As for the second question, you'll need another Array to maintain a sort order of the map keys.

至于第二个问题,您需要另一个 Array 来维护映射键的排序顺序。

var mapKeys = Object.keys(myMap);

mapKeys.sort(function(a,b){return myMap[b].length - myMap[a].length});


Then you can iterate the mapKeysto obtain the collections in your sorted order.

然后,您可以迭代mapKeys以按排序顺序获取集合。

mapKeys.forEach(function(key) {
    console.log("Processing ", key);
    var indices = myMap[key];
});

回答by Sean Vieira

1) Yes, pushwould work (as would unshiftor splice).

1) 是的,push会起作用(就像unshift或 一样splice)。

2) Object keys are inherently unordered and as such they do not have a sortfunction :-) You could add a function to your map to return the values in sorted order however:

2)对象键本质上是无序的,因此它们没有sort函数:-)您可以向地图添加一个函数以按排序顺序返回值:

myMap.sort = function sortMap(sortFunc) {
    var results = [];
    for (key in this) {
        if (this.hasOwnProperty(key) && this[key] !== sortMap) {
            results.push(this[key]);
        }
    }
    return results.sort(sortFunc);
};

myMap.sort(function(a, b) { return a.length - b.length; });

Some notes:

一些注意事项:

  • Don't use Arrayor new Arrayunless you need to (e. g. Array(12).join("-")to create a string of 11 dashes). Instead use the array literal syntax []. It's clearer (and in most browsers actually faster).
  • When in doubt, open up MDN and the console in your browser and try it out.
  • 不要使用Arraynew Array除非您需要(例如Array(12).join("-")创建一个由 11 个破折号组成的字符串)。而是使用数组文字语法[]。它更清晰(并且在大多数浏览器中实际上更快)。
  • 如有疑问,请在浏览器中打开 MDN 和控制台并尝试一下。

回答by ruakh

How would I sort the map so that the keys are ordered by the number of items in their arrays?

我将如何对地图进行排序,以便键按数组中的项目数排序?

Maps are not ordered — there is no difference between { 'cats': [1,4,5], 'dogs': [2,3,6] }and { 'dogs': [2,3,6], 'cats': [1,4,5] }.

地图是无序的——{ 'cats': [1,4,5], 'dogs': [2,3,6] }和之间没有区别{ 'dogs': [2,3,6], 'cats': [1,4,5] }

As for the rest of your question — yes, that's all correct. But instead of writing this:

至于你的其余问题——是的,都是正确的。但不是写这个:

var myMap = {};
myMap["cats"] = new Array(1,4,5);   //animals 1,4,5 are cats
myMap["dogs"] = new Array(2,3,6);   //animals 2,3,6 are dogs  

I'd recommend writing this:

我建议写这个:

var myMap = {
    'cats': [1,4,5], //animals 1,4,5 are cats
    'dogs': [2,3,6]  //animals 2,3,6 are dogs  
};

or perhaps this:

或者这个:

var animals = [ 'cats', 'dogs', 'dogs', 'cats', 'cats', 'dogs' ];