Home > Web Front-end > JS Tutorial > body text

A brief discussion on javascript merge method_basic knowledge

WBOY
Release: 2016-05-16 16:18:50
Original
1151 people have browsed it

ECMAScript5 also adds two new methods for merging arrays: reduce() and reduceRight().

Both of these will iterate over all items of the array
​ ​ ​ reduce(): Traverse from the first item to the end one by one.
​​​​ reduceRight(): Starting from the last item of the array, traverse to the first item of the array.

Both methods accept two parameters: a function to be called on each item (the parameters are: previous value, current value, index of the item, array object)

Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs on the second item of the array,
So the first parameter is the first item of the array, and the second parameter is the second item of the array
          and   are the initial values ​​used as the basis for merging.
​​​​ Use the reduce() method to perform the operation of summing all values ​​in the array, such as:

Copy code The code is as follows:

var values ​​= [1, 2, 3, 4, 5];
        var sum = values.reduce(function (prev, cur, index, array) {
               return prev cur;
        });
alert(sum);
​​​​ //The result is the same, just in the opposite direction
          var sum2=values.reduceRight(function (prev,cur,index,array) {
               return prev cur;
        });
alert(sum2);

Merge sort is an effective sorting algorithm based on merge operations. This algorithm is a very typical application using the divide and conquer method (Divide and Conquer).

Merge sorting method is to merge two (or more) ordered lists into a new ordered list, that is, the sequence to be sorted is divided into several subsequences, and each subsequence is ordered. Then merge the ordered subsequences into the overall ordered sequence.

Merge sort is an effective sorting algorithm based on merge operations. This algorithm is a very typical application using the divide and conquer method (Divide and Conquer). Merge the already ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence orderly, and then make the subsequence segments orderly. If two ordered lists are merged into one ordered list, it is called a 2-way merge.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template