【问题标题】:Second for code only executes for last array item第二个代码仅对最后一个数组项执行
【发布时间】:2020-12-04 23:23:42
【问题描述】:

我的 for 代码只为最后一个数组项运行第二行代码。我怎样才能解决这个问题?使用地图是正确的方法吗?

$(document).ready(function () {

    var data = [{test: "1!", test1: "2!", test2: "3!"}];

    console.log(data);

    data.map(function(item) { 
        for (var key in item) 
            
            console.log (key+": "+item[key]);
            
            console.log ("this will only show on the last item - "+key+": "+item[key]);
            
    }).join();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

【问题讨论】:

  • 你想做什么?

标签: javascript jquery arrays for-loop


【解决方案1】:

因为您没有将代码块放在{}for 中。在这种情况下,只有直接的代码行将被视为for 语句的一部分

$(document).ready(function() {

  var data = [{
    test: "1!",
    test1: "2!",
    test2: "3!"
  }];
  data.map(function(item) {
    for (var key in item) { // changed here , added {}
      console.log(key + ": " + item[key]);
      console.log("this will only show on the last item - " + key + ": " + item[key]);
    }



  }).join();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

【讨论】:

    【解决方案2】:

    添加 for 循环的花括号,它的工作原理

    data.map(function(item) { 
            for (let key in item) {
                console.log (key+": "+item[key]);
                console.log ("this will only show on the last item - "+key+": "+item[key]);
            }        
        }).join();

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2020-08-17
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多