Array reduce and Map methods

Source: Internet
Author: User
Tags javascript array

1. There is an array of length 100, please find out the sum of the first 10 elements of the array in an elegant way

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
sum = 0;

sum = A.slice (0, ten). Reduce (function (pre, current) {
return pre + current;
});

Console.log (sum); 55

2. Do not use loop loops to create an array of length 100, and the value of each element is equal to its subscript.

var a = new Array (100);

A = A.map (function (item, index) {
return index;
});

Using the map method is really high-end atmosphere on the schedule Ah! At first, I thought his answer was correct, but then I printed it on the console and found it wrong, because the final array was an empty array of length 100, as follows:



Curious Strange! Such a good way to output the result is not correct, the heart is tired Ah!

Later, after checking the API, it is known that the JavaScript array is a sparse array, for example, through the new Array (100) to create a novel, although his length is 100, but in fact, he is an empty array, that is, there is no real element. So using the map method does not go through this array 100 times at all. Later, knowing the question, I learned a new feasible method, as follows:


var a = Array (+). Join (","). Split (","). Map (function (item, index) {
return index;
});



Array reduce and Map methods

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.