递归函数返回空数组

时间:2016-09-18 22:46:23

标签: javascript

我创建了以下函数,旨在将字符串拆分为请求的点并返回发生的单词数组。

目前,当参数一个接一个地传递时,该函数可以正常工作,但是当在数组中传递时我不想这两个选项。

如果发现参数是一个数组(第15行),我试图强制该函数重新运行,但是在它运行第二次之后,返回的数组为空。< / p>

问题:

如何修复我的代码,以便即使在数组中传递参数时函数也能正常工作?

代码:

&#13;
&#13;
function string(str) {
  /* Throw error if 'string' is not a string */
  if (str.constructor !== String) throw new Error("Argument is not a string.");
  else return {
    splitAt: function() {
      var
        args = arguments,
        len = args.length,
        arg = args[0],
        index = 0,
        prev = 0,
        arr = [];

      /* If the indices are passed in an array ([4, 5, 8, 12]) rerun the function */
      if (args[0].constructor === Array) string(str).splitAt.apply(this, args[0]);
      else for (; index < len; index++, arg = args[index], prev = args[index - 1]) {
        /* The first time cut the string at the requested point and save both parts */
        if (!index) {
          arr[index] = str.substr(0, arg);
          arr[index + 1] = str.substr(arg);
        
        /* From then on overwrite the last element of the array */
        } else {
          arr[index + 1] = arr[index].substr(arg - prev);
          arr[index] = arr[index].substr(0, arg - prev);
        }
      }
      return arr;
    }
  }
}

/* Arguments passed one after another */
console.log(string("Whatadayit'sbeen!").splitAt(4, 5, 8, 12));

/* Arguments passed in an array */
console.log(string("Whatadayit'sbeen!").splitAt([4, 5, 8, 12]));
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

我想你错过了回归:

alert(obj.foo);
alert(obj.bar);
alert(obj.int);

答案 1 :(得分:1)

我已经完成了所有代码,但修改了接受数组参数的部分。

function string(str) {
  /* Throw error if 'string' is not a string */
  if (str.constructor !== String) throw new Error("Argument is not a string.");
  else return {
    splitAt: function() {
      var
        args = arguments,
        len = args.length,
        arg = args[0],
        index = 0,
        prev = 0,
        arr = [];
    
      /* If the indices are passed in an array ([4, 5, 8, 12]) rerun the function */
      if (args[0].constructor === Array) {
        return string(str).splitAt.apply(this, args[0]);
      } else for (; index < len; index++, arg = args[index], prev = args[index - 1]) {
        /* The first time cut the string at the requested point and save both parts */
        if (!index) {
          arr[index] = str.substr(0, arg);
          arr[index + 1] = str.substr(arg);
            
        /* From then on overwrite the last element of the array */
        } else {
          arr[index + 1] = arr[index].substr(arg - prev);
          arr[index] = arr[index].substr(0, arg - prev);
        }
      }
      return arr;
    }
  }
}
    
/* Arguments passed one after another */
console.log(string("Whatadayit'sbeen!").splitAt(4, 5, 8, 12));
    
/* Arguments passed in an array */
console.log(string("Whatadayit'sbeen!").splitAt([4, 5, 8, 12]));