如何在javascript中使用递归从数组中打印元素

时间:2018-04-09 14:03:28

标签: javascript arrays recursion



Array.prototype.myForEach = function(element) {
  for (var i = 0; i < this.length; i++) {
    element(this[i], i, this);
  }
};

var forArr = ['8', '17', '25', '42','67'];
forArr.myForEach(function(exm){
  console.log(exm);
});
&#13;
&#13;
&#13;

我在表格中写道。你能帮忙把它翻译成递归吗?

3 个答案:

答案 0 :(得分:1)

var forArr = ['8', '17', '25', '42','67'];

var recursive_function = function(array){
  if(array.length > 0){
    console.log(array[0]);
    recursive_function(array.slice(1))
  }
}

recursive_function(forArr)

答案 1 :(得分:0)

Array.shift将在这里诀窍

var forArr = ['8', '17', '25', '42', '67'];

function recursivearray(array) {
  if (array.length > 0) {
    console.log(array.shift());
    recursivearray(array);
  }
}
recursivearray(forArr);

答案 2 :(得分:0)

您可以使用带有附加参数的函数调用作为实际索引。

&#13;
&#13;
Array.prototype.myForEach = function (fn, thisArg, i = 0) {
    if (!(i in this)) {
        return;
    }
    fn.bind(thisArg)(this[i], i, this);
    this.myForEach(fn, thisArg, i + 1);
};

function showValues(v, i, a) {
    console.log(v, i, JSON.stringify(a));
}

[99, 100, 101, 102].myForEach(showValues);
&#13;
&#13;
&#13;