jQuery 遍历javascript中的地图

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

iterate through a map in javascript

javascriptjquerymap

提问by user2374903

I have a structure like this:

我有这样的结构:

var myMap = {
    partnr1: ['modelA', 'modelB', 'modelC'],
    partnr2: ['modelA', 'modelB', 'modelC']
};

I am going to iterate through each of the elements (partnr) with their associatives (models).

我将遍历每个元素(partnr)及其关联(模型)。

I am trying a double $each iteration in order to achieve this, but nothing happens:

我正在尝试双 $each 迭代以实现这一目标,但没有任何反应:

$.each(myMap, function (i, val) {
    $.each(i, function (innerKey, innerValue) {

        setTimeout(function () {
            $('#variant').fadeOut("slow", function () {
                $(this).text(innerKey + "-" + innerValue).fadeIn("slow");

            });

        }, i * 6000);

    });
});

The effect with fading in and out that I am trying to achieve is working fine when using a single value array (Object), but not when I need to have more than one value for each key like here.

当使用单值数组(对象)时,我试图实现的淡入淡出效果很好,但当我需要像这里这样的每个键有多个值时就不行了。

Any ideas of how to accomplish this iteration succesfully and are there other ways than using a map that would be better in this case ?

关于如何成功完成此迭代的任何想法,除了在这种情况下使用地图更好之外,还有其他方法吗?

Any suggestions would be of interest.

任何建议都会很有趣。

回答by Atle

I'd use standard javascript:

我会使用标准的 javascript:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

Note the different ways of treating objects and arrays.

注意处理对象和数组的不同方式。

回答by David Schumann

An answer to your Question from 2019:

对您 2019 年问题的回答:

It depends on what version of ECMAScript you use.

这取决于您使用的 ECMAScript 版本。

Pre ES6:

ES6 前:

Use any of the answers below, e.g.:

使用以下任何答案,例如:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

For ES6 (ES 2015):

对于 ES6 (ES 2015):

You should use a Mapobject, which has the entries()function:

您应该使用一个Map具有以下entries()功能的对象:

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

For ES8 (ES 2017):

对于 ES8(ES 2017):

Object.entries()was introduced:

Object.entries()介绍:

const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
  console.log(key, value);
}

回答by Pointy

The callback to $.each()is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

回调以$.each()该顺序传递属性名称和值。因此,您正在尝试在对 的内部调用中迭代属性名称$.each()。我想你想要:

$.each(myMap, function (i, val) {
  $.each(val, function(innerKey, innerValue) {
    // ...
  });
});

In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

在内部循环中,给定像您的地图这样的对象,值是数组。没关系,但请注意“innerKey”值都是数字。

edit— Now once that's straightened out, here's the next problem:

编辑- 现在一旦理顺,这是下一个问题:

    setTimeout(function () {

      // ...

    }, i * 6000);

The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

第一次通过该循环时,“i”将是字符串“partnr1”。因此,该乘法尝试将导致NaN. 您可以保留一个外部计数器来跟踪外部地图的属性计数:

var pcount = 1;
$.each(myMap, function(i, val) {
  $.each(val, function(innerKey, innerValue) {
    setTimeout(function() {
      // ...
    }, pcount++ * 6000);
  });
});

回答by Pointy

Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.

不要使用迭代器来做到这一点。通过增加回调中的计数器并递归调用下一项的操作来维护您自己的循环。

$.each(myMap, function(_, arr) {
    processArray(arr, 0);
});

function processArray(arr, i) {
    if (i >= arr.length) return;

    setTimeout(function () {
        $('#variant').fadeOut("slow", function () {
            $(this).text(i + "-" + arr[i]).fadeIn("slow");

            // Handle next iteration
            processArray(arr, ++i);
        });
    }, 6000);
}


Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.

尽管您的代码中存在逻辑错误。您正在(大致)同时将同一个容器设置为多个不同的值。也许您的意思是每个人都更新自己的容器。