[JS Practice] Calculating sum of values in array with reduce(使用reduce方法计算数组元素之和)

Title :

Calculating sum of values in array with reduce(使用reduce方法计算数组元素之和)

Description:

Make the sum() function return the sum of the values in the passed in array. Your solution must use the reduce() function of the built-in javascript Array object. If you’re not familiar with reduce(), reading over the documentation may help.

function sum(array) {
  // Use array.reduce() to find and return the
  // sum of the values in array.
}

For example:

var someNumbers = [1,2,3,4,5,6,7,8,9,10];

sum(someNumbers); // should return 55

My solution :

function sum(array) {
  return array.reduce(function(preVal,postVal){
  	return preVal+postVal;
  });
}

此练习的重点在于考察reduce方法的使用。

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s