Jquery每个循环都没有得到最后一个元素

时间:2017-07-02 13:38:42

标签: javascript jquery loops each

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
testArray =[[ 'text1', 'text2', 'text3' ],
    [ 'question',
      'correct answer',
      'second answer',
      'third answer',
      'fourth answer' ],
    [ 'question',
      'correct answer',
      'second answer',
      'third answer',
      'fourth answer',
      'fifth answer',
      'sixth answer' ]];

</script>
</head>

<body>

<div id = "passage"></div>
<div id = "question"></div>
<div id = "answers"></div>

<script>

$.each(testArray[1].slice(1), function (i) {
    $("#answers").append("<p>" + testArray[1][i] + "</p>");
});

</script>

</body>
</html>

当我运行它时,我希望最后一个循环遍历从testArray[1][1]testArray[1][4]的元素。但出于某种原因,它只会达到testArray[1][3]。有谁知道问题是什么?

编辑:

我做了这个,它以某种方式适用于我想做的事情(从index-1元素开始并循环到结尾):

$.each(testArray[1].slice(1), function (i) {
    $("#answers").append("<p>" + testArray[1][i + 1] + "</p>");
});

不确定这是如何/为何有效。

3 个答案:

答案 0 :(得分:0)

这确实很奇怪。我尝试使用ES6版本,它运行得很好:

  testArray[ 1 ].slice( 1 ).forEach( item => {
    $("#answers").append("<p>" + item + "</p>");
  } );

答案 1 :(得分:-1)

编辑

问题是你将切片数组传递给$ .each,但在回调中你正在为原始数组建立索引。

数组$ .each收到的是[&#39;正确答案&#39;,&#39;第二个答案&#39;,&#39;第三个答案&#39;第四个答案&#39; ],但是当你真正想要从你传入的数组中获取你的值时,它会从testArray中获取你的值。一个解决方案是只使用传入的值作为第二个参数回调函数。

&#13;
&#13;
testArray =[[ 'text1', 'text2', 'text3' ],
    [ 'question',
      'correct answer',
      'second answer',
      'third answer',
      'fourth answer' ],
    [ 'question',
      'correct answer',
      'second answer',
      'third answer',
      'fourth answer',
      'fifth answer',
      'sixth answer' ]];

$.each(testArray[1].slice(1), function (i, value) {
    $("#answers").append("<p>" + value + "</p>");
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">


</script>
</head>

<body>

<div id = "passage"></div>
<div id = "question"></div>
<div id = "answers"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

只需添加一个简单的SOCKETS = [] of HTTP::WebSocket ws "/chat" do |socket,env| room = env.params.query["room"] SOCKETS << socket socket.on_message do |message| SOCKETS.each { |socket| socket.send message} end socket.on_close do SOCKETS.delete socket end end 条件,下面是代码:

&#13;
&#13;
if
&#13;
testArray = [
  ['text1', 'text2', 'text3'],
  ['question',
    'correct answer',
    'second answer',
    'third answer',
    'fourth answer'
  ],
  ['question',
    'correct answer',
    'second answer',
    'third answer',
    'fourth answer',
    'fifth answer',
    'sixth answer'
  ]
];

$.each(testArray[1], function(i) {
  if (i > 0)
    $("#answers").append("<p>" + testArray[1][i] + "</p>");
});
&#13;
&#13;
&#13;