【问题标题】:My loop is not moving on to the next element in array我的循环没有移动到数组中的下一个元素
【发布时间】:2020-09-22 21:05:44
【问题描述】:

跟进我之前的question。我正在尝试运行一个递归函数来一次处理一个数组中的一个元素。我,它不希望它处理第一个元素并且在第一个元素的处理完成之前不开始处理列表中的下一个元素?

这是我的数组:arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(` 
                <tr id='tr_${d}'>
                    <td'>${d}</td>
                    <td><i id='change' class='no'></i></td>
                </tr>
            `);
});
let finished = 1;
for (let i = 0; i <= arr.length; i++) {
   if (finished === 1 && arr.length !== 0) {
       hp_name = arr[i];
       finished = 0;
    }

   if(finished == 0) {
    const myfunc = () => {
     json_object['name'] = hp_name;
     $.post(api, json_object,
        function(data, status) {
           if (data.value === 'started') {
           setTimeout(myfunc, 5000);
        } else {
           finished = 1;
           $('#change').removeClass('no').addClass('yes');
        }
     }, 'json');
   }
   myfunc();
   if (finished === 1) continue;
   }
}

上面的这个逻辑只适用于第一个元素,然后停止。为什么它不移动到数组中的下一个元素并处理它?

它没有移动到数组中的下一个元素。

【问题讨论】:

  • 我看不到递归在哪里。这个代码是myfunc吗?递归函数通常需要参数,因此您可以在递归调用中更改它们并更接近基本情况。
  • @Barmar 抱歉,我刚刚将 myFunc 添加到代码中。对不起,我是递归的新手。你能帮我解决我的问题吗?
  • @Barmar,我也编辑了我的问题。如何进入下一个元素?
  • 为什么循环使用data.length作为限制而不是arr.length?另外,测试应该是&lt; 而不是&lt;=
  • $.post 是异步的。所有循环迭代都将在设置 finished = 1 之前运行。

标签: javascript jquery arrays loops post


【解决方案1】:

不要使用for 循环。将数组索引作为参数传递给函数,并在进行递归调用时递增。

const myfunc = (i) => {
  if (i >= arr.length) {
    return;
  }
  json_object['name'] = arr[i];
  $.post(api, json_object,
    function(data, status) {
      if (data.value === 'started') {
        setTimeout(function() {
          myfunc(i+1);
        }, 5000);
      } else {
        $('#change').removeClass('no').addClass('yes');
      }
    }, 'json');
}
myfunc(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多