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