重写展平功能

时间:2015-08-26 22:33:14

标签: javascript arrays underscore.js

我已经编写了一个下划线_.flatten函数的版本,它可以工作,但我不明白为什么第一个工作但不是第二个版本。

var flatten = function (array, result) {
  var result = [];
  for (var i = 0; i < array.length; i++) {
    var current = array[i];
    if (Array.isArray(current)) {
      result.push.apply(array, flatten(current));
    }
    else {
      result.push(current);
    }
  }
  return result;
};

var nested = [1, [2], [3, [[[4]]]]];
console.log(flatten(nested));
// [1,2,3,4]

VS

var flatten = function (array, result) {
  var result = [];
  array.forEach(function (current) {
    if (Array.isArray(current)) {
      result.push.apply(array, flatten(current));
    }
    else {
      result.push(current);
    }
  });
  return result;
};
var nested = [1, [2], [3, [[[4]]]]];
console.log(flatten(nested));
// [1]

0 个答案:

没有答案