Array Summation Method of JavaScript learning notes, javascript learning notes

Source: Internet
Author: User
Tags javascript array

Array Summation Method of JavaScript learning notes, javascript learning notes

Recommended reading:Add, delete, modify, and query the array of JavaScript learning notes

Recently, I have learned more and more about the power and charm of JavaScript. Just an array of knowledge points has made me a beginner like me a long time. Tossing is tossing, but it is still very effective. Some basic knowledge learned over the past few days has been used in your own business. I feel confident that I can learn JavaScript one day.

Let's talk about nothing more. Let's take a look at the array summation today to see which methods can be used to achieve the array summation.

Array Method

There are many methods for arrays in JavaScript to better illustrate how many JavaScript methods can be used:

Let's briefly review the previous knowledge:

Push (): Add one or more elements to the end of the array.

Unshift (): Add one or more elements to the beginning of the array.

Pop (): deletes the last element of the array.

Shift (): deletes the first element of the array.

Sort (): sorts arrays.

Reverse (): reversing the position of an array item in the array

Concat (): merges arrays.

Slice (): deletes the specified array entry at the specified position, and constructs the deleted array entry into a new array.

Splice (): deletes, inserts, and replaces an array.

IndexOf (): locate the element in the array from the front to the back

LastIndexOf (): returns the position of the element in the array from the back to the front.

ForEach (), every (), some (), filter (), and map (): array Iteration

Reduce (): Each value in the array (from left to right) is merged into a value.

ReduceRight (): merges each value in the array (from right to left) into a value.

Array summation

In today's use case, suppose we have an array like this:

var arr = [0,1,2,3,4,5,6,7,8,9];

Add the item values in the array to 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9. What should we do, or what methods can be implemented. To put it simply, you can try to add up array items one by one. Is array iteration necessary? Can we also use these methods to sum arrays?

For Loop and while LOOP

The first thought is the two loop methods, which were also tried in the previous section. Again:

// Sum: for Loop traversal array arr (function () {var sum = 0; function getSum (array) {for (var I = 0; I <array. length; I ++) {sum + = parseInt (array [I]);} return sum;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {sum = 0; getSum (arr);} console. timeEnd ("getSum"); // 7877.155msconsole.log ("use for loop: sum =" + sum); // 45 })();

Let's change the while to see:

(Function () {var sum = 0; function getSum (array) {var I = array. length; while (I --) {sum + = parseInt (array [I]);} return sum;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {var sum = 0; getSum (arr);} console. timeEnd ("getSum"); // getSum: 7690.056 ms console. log ("use while loop: sum =" + sum); // use while loop: sum = 45 })();

In addition to the old for and while loops, other array iteration methods are added to ES5, such as forEach (), every (), some (), and filter () and map. These methods allow each element in the array to execute a callback function. If you only need to accumulate an array item for this callback function:

function getSum (item, index, array){sum += item;}

ForEach () method

The forEach () method allows each array to execute the specified callback function callbackfn. In this way, we can perform an accumulation calculation in the callback function getSum.

(Function () {var sum = 0; function getSum (item, index, array) {sum + = item;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {var sum = 0; arr. forEach (getSum);} console. timeEnd ("getSum"); // getSum: 1348.212msconsole.log ("use forEach loop: sum =" + sum); // use forEach loop: sum = 45 })()

Some () method

(Function () {var sum = 0; function getSum (item, index, array) {sum + = item;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {var sum = 0; arr. some (getSum);} console. timeEnd ("getSum"); // getSum: 1038.737msconsole.log ("use some loop: sum =" + sum); // use some loop: sum = 45 })()

Map () method

(Function () {var sum = 0; function getSum (item, index, array) {sum + = item;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {var sum = 0; arr. map (getSum);} console. timeEnd ("getSum"); // getSum: 4568.558msconsole.log ("Use map loop: sum =" + sum); // use map loop: sum = 45 })()

Filter () method

(Function () {var sum = 0; function getSum (item, index, array) {sum + = item;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {var sum = 0; arr. filter (getSum);} console. timeEnd ("getSum"); // getSum: 111720.39msconsole.log ("Use filter loop: sum =" + sum); // use filter loop: sum = 45 })()

Every () method

The every () method is slightly different from the previous methods, because the every () method returns only when the result of executing the callback function in the array is set to true. Otherwise, false is returned. Because in the previous callback function, you need to add return true;

(Function () {var sum = 0; function getSum (item, index, array) {sum + = item; return true; // Since the every method will stop traversing when the first false value returned by the callback function is returned, it must always return true}; console. time ("getSum"); for (var I = 0; I <1000000; I ++) {sum = 0; arr. every (getSum);} console. timeEnd ("getSum"); // 1028.892msconsole.log ("use every loop: sum =" + sum); // use every loop: sum = 45 })();

Reduce () and reduceRight () Methods

The reduce () and reduceRight () methods can accept a callback function callbackfn as an accumulator. Each value in the array (from left to right) is merged and eventually becomes a value. In this way, each element of the array can be accumulated to achieve the array summation function.

First, create a callback function for the accumulators:

function getSum(preValue,curValue,index,array) {return preValue += curValue;}

Take the preceding array as an example:

Function getSum (preValue, curValue, index, array) {return preValue + curValue;} console. time ("getSum"); for (var I = 0; I <1000000; I ++) {sum = arr. reduce (getSum, 0)} console. timeEnd ("getSum"); // 3257.201msconsole.log ("use reduce loop: sum =" + sum); // use reduce loop: sum = 45

In the previous test, the reduce () method took the shortest time. In this test, it seems that the time was the longest. I don't know where the error occurred. I hope you can guide me.
The reduceRight () method is the same as the reduce () method, but it accumulates from the right side of the array to the left.

Summary

After one operation, the sum of arrays is basically achieved through array traversal, so you can easily achieve the sum of arrays by mastering various traversal methods in the array. Although these traversal methods can achieve the sum of arrays, different methods have different performance. The examples in this article may not fully describe their performance comparison. If you have better suggestions, please share them.

The above is a full introduction to the array Summation Method of JavaScript learning notes. I hope it will be helpful to you!

Articles you may be interested in:
  • How to Implement random array sorting using JavaScript
  • Javascript array random sorting instance analysis
  • Add, delete, modify, and query the array of JavaScript learning notes
  • Random sorting of JavaScript learning notes Array

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.