Javascript中reduce回调中的第二个参数

2nd argument in reduce callback in Javascript

本文关键字:第二个 参数 回调 reduce Javascript      更新时间:2023-09-26

var reverse = function (list) {
  return list.reduce(function (reversedList, current) {
    return [ current ].concat(reversedList);
  }, []);
};
console.log(reverse([1,2,3,4]));

所以这是为了使用reduce在Javascript中反转数组。根据MDNs参考。如果没有提供initialValue,则第二个参数(此处为current)是数组第一个元素之后的第二个元素。但在这种情况下,电流不是阵列的第二个元素,而是阵列的最后一个元素。为什么会这样?

您可以在控制台上为某些数组[1、2、3、4]运行此代码,当前将返回4。

执行以下操作时,您的代码正在创建一个包含当前项的新数组:[current]然后将"reversedList"数组连接在其后面。

var reverse = function (list) {
  return list.reduce(function (reversedList, current) {
    //this creates a new array with just the "current" item in it
    //and then concatenates the "reversedList" array with it.
    console.log("concatenating ", current, "with", reversedList); 
    return [ current ].concat(reversedList);
  }, []);
};
console.log(reverse([1,2,3,4]));

这是一种奇怪的方式,但我认为这只是出于教育目的。您可以将每个项添加到数组的开头,而不是串联。

 var reverse = function (list) {
  return list.reduce(function (reversedList, current) {
    reversedList.unshift(current);
    return reversedList;
  }, []);
};
console.log(reverse([1,2,3,4]));

也就是说,如果你只是想反转一个数组,你可以使用reverse()方法:

console.log([1,2,3,4].reverse());