Detailed description of JavaScript reduce and reduceRight, reducereduceright

Source: Internet
Author: User

Detailed description of JavaScript reduce and reduceRight, reducereduceright

Reduce method (ascending)

Syntax:

Array1.reduce (callbackfn [, initialValue])

Parameters

Definition

Array1

Required. An array object.

Callbackfn

Required. A function that accepts up to four parameters. For each element in the array, the reduce method calls the callbackfn function once.

InitialValue

Optional. If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function will provide this value as a parameter rather than an array value.

Return Value:

The cumulative result obtained by calling the callback function for the last time.

Exception:

If any of the following conditions is met, a TypeError exception occurs:

  1. The callbackfn parameter is not a function object.
  2. The array does not contain elements and does not provide initialValue.

Callback Function Syntax:

Function callbackfn (previusvalue, currentValue, currentIndex, array1)

You can use up to four parameters to declare the callback function.

The following table lists callback function parameters.

Callback Parameters

Definition

Previusvalue

The value obtained by calling the callback function last time. If initialValue is provided to the reduce method, the previusvalue is initialValue when the function is called for the first time.

CurrentValue

The value of the current array element.

CurrentIndex

Numeric index of the current array element.

Array1

Array object that contains this element.

The first time a callback function is called

When the callback function is called for the first time, the value provided as a parameter depends on whether the reduce method has the initialValue parameter.

If initialValue is provided to the reduce method:

The previusvalue parameter is initialValue.
The currentValue parameter is the value of the first element in the array.

If initialValue is not provided:

The previusvalue parameter is the value of the first element in the array.
The currentValue parameter is the value of the second element in the array.

Modify an array object

The array object can be modified by the callback function.

The following table describes the results of modifying the array object after the reduce method is started.

Conditions after the reduce method is started

Whether the element is passed to the callback function

Add an element outside the original length of the array.

No.

Add an element to fill in the elements missing from the array.

Yes, if the index has not been passed to the callback function.

The element is changed.

Yes, if this element has not been passed to the callback function.

Deletes an element from an array.

No, unless the element has been passed to the callback function.

Instance:

1. In the following example, the array values are connected to strings, and each value is separated. Because the reduce method does not provide an initial value, "abc" is used as the previusvalue parameter when the callback function is called for the first time, and "def" is used as the currentValue parameter.

function appendCurrent (previousValue, currentValue) { return previousValue + "::" + currentValue; }var elements = ["abc", "def", 123, 456];var result = elements.reduce(appendCurrent);document.write(result);// Output:// abc::def::123::456

2. The following example adds the rounded value to the array. Call the reduce method with the initial value 0.

function addRounded (previousValue, currentValue) { return previousValue + Math.round(currentValue); }var numbers = [10.9, 15.4, 0.5];var result = numbers.reduce(addRounded, 0);document.write (result);// Output: 27

3. The following example adds a value to the array. The currentIndex and array1 parameters are used for callback functions.

function addDigitValue(previousValue, currentDigit, currentIndex, array) { var exponent = (array.length - 1) - currentIndex; var digitValue = currentDigit * Math.pow(10, exponent); return previousValue + digitValue; }var digits = [4, 1, 2, 5];var result = digits.reduce(addDigitValue, 0);document.write (result);// Output: 4125

Analysis of this question:

First, the initial value 0 is assigned, so currentDigit starts from 4 and calls the method four times. In this way, the parameters of the four call methods can be written as follows: (0, 4, 0, array), (, 1, array), (, 2, array), (, 3, array), again calculated because the initial value is 0, all you need to calculate the sum of the return values of each method. If array. length is always 4, the values calculated for the four times are 4000 + 100 + 20 + 5 = 4125, respectively.

ReduceRight method (descending)

The reduceRight syntax and callback function rules are the same as the reduce method. The difference is that they are in ascending order with reduce, that is, the badge starts from 0, while reduceRight is in descending order, that is, badge from arr. start with length-1. If an initial value exists, it is calculated starting from the last number. If no initial value exists, the previusvalue parameter is the value of the last element in the array, and currentValue is the value of the second to last element in the array.

Example:

1. The following example gets the element with a value between 1 and 10 in the array. The initial value provided to the reduceRight method is an empty array.

function Process2(previousArray, currentValue) { var nextArray; if (currentValue >= 1 && currentValue <= 10)  nextArray = previousArray.concat(currentValue); else  nextArray = previousArray; return nextArray;}var numbers = [20, 1, -5, 6, 50, 3];var emptyArray = new Array();var resultArray = numbers.reduceRight(Process2, emptyArray);document.write("result array=" + resultArray);// Output:// result array=3,6,1

2. The reduceRight method can be applied to strings. The following example shows how to use this method to reverse the characters in a string.

function AppendToArray(previousValue, currentValue) { return previousValue + currentValue;}var word = "retupmoc";var result = [].reduceRight.call(word, AppendToArray, "the ");// var result = Array.prototype.reduceRight.call(word, AppendToArray, "the ");document.write(result);// Output:// the computer

Here, you can use an empty array to call the reduceRight method and use the call method to introduce the parameter. It can also be called directly by using the prototype chain, that is, Array. prototype. reduceRight. call (word, AppendToArray, "");

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.