iterate through a map in javascript

后端 未结 5 1585
温柔的废话
温柔的废话 2021-02-01 13:13

I have a structure like this:

var myMap = {
    partnr1: [\'modelA\', \'modelB\', \'modelC\'],
    partnr2: [\'modelA\', \'modelB\', \'modelC\']
};
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 13:54

    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.

提交回复
热议问题