我在javascript中创建了一个递归函数,用于过滤掉输入数组中的字符串。为什么它会额外经过for循环3次?

时间:2020-12-11 07:41:19

function filter_list(l) {

  var count = l.length;
  console.log('the count is:', count);

  function loop() {
    for (var i = 0; i < count; i++) {
      var type = (typeof l[i]);

      if (type == 'string') {
        l.splice(i, 1);
        console.log('the list is', l);
        filter_list(l);
      } else {
        console.log('this item is', l[i], 'the list is', l);
      }
    }
  }

  loop()
}

filter_list([1, 2, 'a', 'c', 'd']);

Essentially, it does get the job done, however for the final for loop, I am not sure why it runs through it 3 extra times? Would anyone be able to shed some light on this?

从本质上讲,它确实完成了工作,但是对于最终的for循环,我不确定为什么它会经过3次额外的时间?有人能够对此有所了解吗?

1 个解决方案

#1


0  

I know this isn't a direct answer to your question, but if all you need to do is filter strings out of an array, you could more easily do this with Array.prototype.filter():

我知道这不是你问题的直接答案,但如果你需要做的就是从数组中过滤掉字符串,你可以使用Array.prototype.filter()更容易地做到这一点:

[1, 2, 'a', 'c', 'd'].filter(function(i) { return typeof i !== 'string' });

JSFiddle

Or, if you want to keep it as a standalone function:

或者,如果您想将其保留为独立功能:

function filter_list(array) {
  return array.filter(function(i) { return typeof i !== 'string' });
}

#1


0  

I know this isn't a direct answer to your question, but if all you need to do is filter strings out of an array, you could more easily do this with Array.prototype.filter():

我知道这不是你问题的直接答案,但如果你需要做的就是从数组中过滤掉字符串,你可以使用Array.prototype.filter()更容易地做到这一点:

[1, 2, 'a', 'c', 'd'].filter(function(i) { return typeof i !== 'string' });

JSFiddle

Or, if you want to keep it as a standalone function:

或者,如果您想将其保留为独立功能:

function filter_list(array) {
  return array.filter(function(i) { return typeof i !== 'string' });
}