循环遍历数组返回undefined?

时间:2017-10-05 03:38:06

标签: javascript arrays

如下所示,我循环遍历一个对象数组,但问题是retrieve [i]在控制台中以未定义的形式返回。为什么呢?

$(document).ready(function() {
  var retrieve = [
    {
      title: "SampleTitle-1",
      url: "SampleUrl-1"
    },
    {
      title: "SampleTitle-2",
      url: "SampleUrl-2"
    },
    {
      title: "SampleTitle-3",
      url: "SampleUrl-3"
    }
  ];

  for (var i = 0; i <= retrieve.length; i++) {
    $("ul").append("<li><a href='" + retrieve[i].url + "'>" + retrieve[i].title + "</a></li>");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>



</ul>

我是否遗漏了语法错误?

很抱歉,如果答案看起来非常明显,但我还在学习Javascript。

无论如何,提前感谢您的回答和评论:)

2 个答案:

答案 0 :(得分:0)

应该 i < retrieve.length 而不是 i <= retrieve.length.

for(var i = 0; i < retrieve.length; i++) {
 $("ul").append("<li><a href='" + retrieve[i].url + "'>" +         retrieve[i].title + "</a></li>");
}

<强>样本

&#13;
&#13;
$(document).ready(function (){	
			var retrieve =
			[{

				title: "SampleTitle-1",
				url: "SampleUrl-1"
			},
			{
				title: "SampleTitle-2",
				url: "SampleUrl-2"
			},
			{
				title: "SampleTitle-3",
				url: "SampleUrl-3"
			}];
			for(var i = 0; i < retrieve.length; i++) {
				$("ul").append("<li><a href='" + retrieve[i].url + "'>" +         retrieve[i].title + "</a></li>");
			}
			
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

for循环中的迭代次数多于数组中的元素数。它应该是i < retrieve.length而不是i <= retrieve.length

&#13;
&#13;
$(document).ready(function() {

  var retrieve = [

    {

      title: "SampleTitle-1",
      url: "SampleUrl-1"

    },


    {

      title: "SampleTitle-2",
      url: "SampleUrl-2"

    },


    {

      title: "SampleTitle-3",
      url: "SampleUrl-3"

    }

  ];

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

    $("ul").append("<li><a href='" + retrieve[i].url + "'>" + retrieve[i].title + "</a></li>");

  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>



</ul>
&#13;
&#13;
&#13;