JavaScript reduce and reduceright detailed _javascript tips

Source: Internet
Author: User

Reduce method (Ascending)

Grammar:

Array1.reduce (callbackfn[, InitialValue])

Parameters

Defined

Array1

Necessary. An array object.

Callbackfn

Necessary. 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 an initial value to start the rollup. The first call to the CALLBACKFN function provides this value as an argument rather than an array value

return value:

The cumulative result obtained by the last call to the callback function.

Abnormal:

A TypeError exception is thrown when either of the following conditions is true:

    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 (Previousvalue, CurrentValue, Currentindex, array1)

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

The following table lists the callback function parameters.

Callback Parameters

Defined

Previousvalue

The value obtained through the last call to the callback function. If you provide initialvalue to the reduce method, the Previousvalue is initialvalue when the function is first invoked.

CurrentValue

The value of the current array element.

Currentindex

The numeric index of the current array element.

Array1

The array object that contains the element.

Call callback function for the first time

When the callback function is invoked for the first time, the value supplied as a parameter depends on whether the reduce method has initialvalue parameters.

If you provide initialvalue to the reduce method:

The Previousvalue parameter is initialvalue.
The CurrentValue parameter is the value of the first element in the array.

If InitialValue is not provided:

The Previousvalue parameter is the value of the first element in the array.
The CurrentValue parameter is the value of the second element in the array.

Modifying an Array object

Array objects can be modified by callback functions.

The following table describes the results obtained when modifying the array object after the reduce method starts.

Conditions after the reduce method starts

Whether the element is passed to the callback function

Adds an element outside the original length of the array.

Whether.

Add elements to populate the missing elements in the array.

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

element is changed.

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

Deletes an element from the array.

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

Instance:

1. The following example joins an array value to a string, with each value separated by "::". Because the reduce method is not supplied with an initial value, the first call to the callback function takes "abc" as the Previousvalue parameter and "Def" 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::D ef::123::456

2. The following example adds a rounded value to an array. Use the initial value of 0 to invoke the reduce method.

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 an array. Currentindex and Array1 parameters for callback functions

function Adddigitvalue (Previousvalue, Currentdigit, Currentindex, array) {
 var exponent = (array.length-1)-current Index;
 var digitvalue = Currentdigit * MATH.POW (ten, exponent);
 return previousvalue + digitvalue;
 }
var digits = [4, 1, 2, 5];
var result = Digits.reduce (adddigitvalue, 0);
document.write (result);
output:4125

This problem analysis:

First given the initial value of 0, then Currentdigit is starting from 4, calling the method four times, so that you can write the parameters of the Four method calls: (0,4,0,array), (4,1,1,array), (1,2,2,array), (2,5,3, Array), once again, because the initial value is 0, all you need to calculate the return value of each method is finally added. Array.Length is always 4, then the four calculated values are 4000+100+20+5=4125

Reduceright Method (Descending)

The reduceright syntax and the rules of the callback function are the same as the reduce method, except that the difference is in ascending order with reduce, that is, the angle is starting at 0, and the reduceright is descending, that is, the corner mark starts with the arr.length-1. If there is an initial value, the calculation begins with the last number, and if there is no initial value, the Previousvalue parameter is the value of the last element in the array, CurrentValue is the value of the second-lowest element in the array.

Example:

1. The following example gets the elements in the array with values from 1 through 10. The initial value provided to the Reduceright method is an empty array.

function Process2 (Previousarray, currentvalue) {
 var nextarray;
 if (currentvalue >= 1 && currentvalue <=)
  Nextarray = Previousarray.concat (currentvalue);
 else
  nextarray = Previousarray;
 return nextarray;
}
var numbers = [1, -5, 6, 3];
var emptyarray = new Array ();
var resultarray = Numbers.reduceright (Process2, emptyarray);
document.write ("result array=" + resultarray);
Output:
//Result array=3,6,1

The 2.reduceRight method can be applied to strings. The following example shows how to use this method to reverse a character 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 invoke the Reduceright method directly using an empty array, and introduce the parameters using the call method. It can also be called directly using the prototype chain, i.e. Array.prototype.reduceRight.call (Word, Appendtoarray, "the");

Thank you for reading, I hope to help you, thank you for your support for this site!

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.