JavaScript数组方法终极指南-精简

The reduce() method reduces an array of values down to just one value. The single value that is returned can be of any type.

reduce()方法将值数组减少为一个值。 返回的单个值可以是任何类型。

reduce() is like the Swiss Army knife of array methods. While others like map() and filter() provide specific functionality, reduce() can be used to transform an input array into any output you desire, all while preserving the original array.

reduce()就像瑞士军刀的数组方法。 虽然诸如map()filter()类的其他函数提供了特定的功能,但reduce()可以用于将输入数组转换为所需的任何输出,同时保留原始数组。

句法 (Syntax)

const newValue = arr.reduce(function(accumulator, currentValue, index, array) {
  // Do stuff with accumulator and currentValue (index, array, and initialValue are optional)
}, initialValue);
  • newValue - the new number, array, string, or object that is returned

    newValue的新数字,数组,字符串或对象

  • arr - the array being operated on

    arr在其上操作的数组

  • accumulator - the returned value of the previous iteration

    accumulator -上一次迭代的返回值

  • currentValue - the current item in the array

    currentValue数组中的当前项目

  • index - the index of the current item

    index当前项目的索引

  • array - the original array on which reduce() was called

    array在其上调用reduce()的原始数组

  • initialValue - a number, array, string, or object that serves as an initial value for the eventual output

    initialValue一个数字,数组,字符串或对象,用作最终输出的初始值

例子 (Examples)

ES5 (ES5)

var numbers = [1, 2, 3]; 

var sum = numbers.reduce(function(total, current) {
  return total + current;
}, 0);

console.log(numbers); // [1, 2, 3]
console.log(sum); // 6

ES6 (ES6)

const numbers = [1, 2, 3];

const sum = numbers.reduce((total, current) => {
  return total + current;
}, 0);

const sumOneLiner = numbers.reduce((total, current) => total + current, 0);

console.log(numbers); // [1, 2, 3]
console.log(sum); // 6
console.log(sumOneLiner); // 6

关于initialValue (All About initialValue)

提供的initialValue (initialValue Provided)

The initialValue argument is optional. If provided, it will be used as the initial accumulator value (total) in the first call to the callback function:

initialValue参数是可选的。 如果提供的话,它将在第一次调用回调函数时用作初始累加器值( total ):

const numbers = [2, 3, 4];
const product = numbers.reduce((total, current) => {
  return total * current;
}, 1);

console.log(product); // 24

Since the initialValue of 1 is provided after the callback function, the reduce() starts at the beginning of the array and sets the first element (2) as the current value (current). It then iterates through the rest of the array, updating the accumulator value and current value along the way.

由于在回调函数之后提供了initialValue 1,因此reduce()从数组的开头开始,并将第一个元素(2)设置为当前值( current )。 然后,它将遍历数组的其余部分,并一路更新累加器值和当前值。

忽略了initialValue (initialValue Omitted)

If initialValue is not provided, the iteration will start at the second element in the array (at index 1), with accumulator equal to the first element in the array and currentValue equal to the second element:

如果未提供initialValue ,则迭代将从数组中的第二个元素(索引1)开始, accumulator等于数组中的第一个元素, currentValue等于第二个元素:

const numbers = [2, 3, 4];
const product = numbers.reduce((total, current) => {
  return total * current;
});

console.log(product);

In this example, no initialValue is provided, so reduce() sets the first element of the array as the accumulator value (total is equal to 2), and sets the second element of the array as the current value (currentValue is equal to 3). It then iterates through the rest of the array.

在此示例中,未提供initialValue ,因此reduce()将数组的第一个元素设置为累加器值( total等于2),并将数组的第二个元素设置为当前值( currentValue等于3 )。 然后,它遍历数组的其余部分。

When reducing an array of strings:

减少字符串数组时:

const strings = ['one', 'two', 'three'];
const numberString = strings.reduce((acc, curr) => {
  return acc + ', ' + curr;
});

console.log(numberString); // "one, two, three"

While it's easy to omit the initialValue argument if your reduce() method will return a number or a simple string, you should include one if it will return an array or object.

如果reduce()方法返回一个数字或一个简单的字符串,可以很容易地省略initialValue参数,但是如果它返回一个数组或对象,则应该包括一个。

返回对象 (Returning an Object)

Transforming an array of strings into a single object that shows how many times each string appears in the array is simple. Just pass an empty object ({}) as the initialValue:

将字符串数组转换为单个对象很简单,该对象显示了每个字符串出现在数组中的次数。 只需传递一个空对象( {} )作为initialValue

const pets = ["dog", "chicken", "cat", "dog", "chicken", "chicken", "rabbit"];

const petCounts = pets.reduce(function(obj, pet) {
  if (!obj[pet]) {
    // if the pet doesn't yet exist as a property of the accumulator object,
    //   add it as a property and set its count to 1
    obj[pet] = 1;
  } else {
    // pet exists, so increment its count
    obj[pet]++;
  }
  
  return obj; // return the modified object to be used as accumulator in the next iteration
}, {}); // initialize the accumulator as an empty object

console.log(petCounts);
/*
{
  dog: 2, 
  chicken: 3, 
  cat: 1, 
  rabbit: 1 
}
*/

返回和数组 (Returning and Array)

Generally, if you plan to return an array, map() is often a better option. It tells the compiler (and others reading your code) that every element in the original array will be transformed and returned as a new array of equal length.

通常,如果您计划返回数组,则map()通常是一个更好的选择。 它告诉编译器(和其他阅读您代码的人)原始数组中的每个元素都将被转换并以等长的新数组形式返回。

On the other hand, reduce() indicates that all elements of the original array will get transformed into a new value. That new value could be an array, the length of which might be different than the original.

另一方面, reduce()表示原始数组的所有元素都将转换为新值。 该新值可以是一个数组,其长度可能与原始数组不同。

Say you have a shopping list as an array of strings, but you want to remove all of the foods that you don't like from the list. You could use filter() to filter out everything you don't like and map() to return a new array of strings, or you could just use reduce():

假设您有一个购物清单,其中包含字符串,但您想从清单中删除所有您不喜欢的食物。 您可以使用filter()过滤掉所有您不喜欢的内容,并使用map()返回新的字符串数组,也可以只使用reduce()

const shoppingList = ['apples', 'mangoes', 'onions', 'cereal', 'carrots', 'eggplants'];
const foodsIDontLike = ['onions', 'eggplants'];
const newShoppingList = shoppingList.reduce((arr, curr) => {
  if (!foodsIDontLike.includes(curr)) {
    arr.push(curr);
  }
  
  return arr;
}, []);

console.log(newShoppingList); // ["apples", "mangoes", "cereal", "carrots"]

That's all you need to know about the reduce() method. Like a Swiss Army knife, it's not always the best tool for the job. But you'll be glad to have it in your back pocket when you really need it.

这就是有关reduce()方法的全部知识。 就像瑞士军刀一样,它并不总是工作的最佳工具。 但是当您真正需要它时,您会很高兴将其放在后袋中。

翻译自: https://www.freecodecamp.org/news/the-ultimate-guide-to-javascript-array-methods-reduce/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值