让我们说我使用递归将数组乘以一个数字,哪个版本的性能更好?
版本1: - 没有关闭
var recursiveMultiplier = function(arr, num) {
if (!arr.length) {
return arr;
}
var lastElement = arr.pop();
recursiveMultiplier(arr, num);
arr.push(lastElement * num);
return arr;
}
var x = [1, 2, 3],
num = 2;
var y = recursiveMultiplier(x, num);
console.log(y);

版本2: - 关闭
var recursiveMultiplier = function(arr, num) {
var newArray = [];
var mult = function(a) {
if (a.length) {
newArray[a.length - 1] = a.pop() * num;
mult(a);
return newArray;
}
return;
}
return mult(arr);
}
var x = [1, 2, 3],
num = 2;
var y = recursiveMultiplier(x, num);
console.log(y);