无法在for循环中检索数组值

时间:2017-01-12 11:53:58

标签: javascript jquery arrays for-loop

我有一个快速的noob问题:我正在尝试检索数组的值并使用jQuery"在Click"上将它们打印到html元素。但是,我似乎无法检索数组元素。对于每个单击的项,它应该在索引i处获取数组元素,因此#item-0应该获得"red"等的值。

控制台记录undefined



var descriptions = ["red", "blue", "green", "purple", "white", "black"];

for (var i = 0; i < descriptions.length; i++) {
  $("#item-" + i).on("click", function() {
    var currentDescr = descriptions[i];
    console.log(currentDescr);

    $("#footer-text").html(currentDescr);
  });
};
&#13;
.as-console-wrapper{top:0;max-height:100%;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

它正在发生,因为当您点击按钮时,i的值将为descriptions.length(此时循环正在中断),因为该索引上没有值,它将是undefined

您可以使用提供块级范围的let代替var来解决此问题。

var descriptions = ["red","blue","green","purple","white","black"];


for (let i = 0; i < descriptions.length; i++) {
  $("#item-"+i).on("click", function(){
    var currentDescr = descriptions[i];
    console.log(currentDescr);
    $("#footer-text").html(currentDescr);
  });
};

或使用closure function并传递i作为参数。

var descriptions = ["red","blue","green","purple","white","black"];


for (let i = 0; i < descriptions.length; i++) {
  (function(index){
    $("#item-" + index).on("click", function(){
      var currentDescr = descriptions[index];
      console.log(currentDescr);
      $("#footer-text").html(currentDescr);
    });
  })(i);
};

答案 1 :(得分:2)

循环在事件触发前完成,导致i的值不正确...试试这个:

var descriptions = ["red","blue","green","purple","white","black"];


for (var i = 0; i < descriptions.length; i++) {

    (function(i){
        $("#item-"+i).on("click", function(){

           var currentDescr = descriptions[i];
           console.log(currentDescr);
           $("#footer-text").html(currentDescr);

       });
    }(i));
};