简体   繁体   中英

For Loop that calculates sum of squred numbers in array

I am working on a challenge and in need of some help: Write a for loop that calculates sum of squares of items in an array of numbers. Example: For array [ 1, 2, 3, 4 ] it calculates the sum of squares as 30 (ie 1 + 4 + 9 + 16). I have a fiddle set up if anyone wants to have a closer look. Thanks for your help!

https://jsfiddle.net/jamie_shearman/2drt56e3/23/

var aFewNumbers = [ 1, 2, 3, 7 ];

var squareOfAFewNumbers = 0;

for( var i = 0; i <= aFewNumbers; i++ ) {
    squareOfAFewNumbers = squareOfAFewNumbers * aFewNumbers[i] ;
  }

console.log( squareOfAFewNumbers );

Your math is wrong. As an obvious issue, the variable starts at 0 and then is multiplied by each array element; 0 times anything is 0, so it will always remain 0 no matter what the values are. Not to mention your loop isn't looking at the length of the array as a stopping condition, which it should be, since you want to iterate from the beginning to the end of the array.

You need to iterate through to the array's length, square each array element, and add that square to the variable:

for( var i = 0; i < aFewNumbers.length; i++ ) {
    squareOfAFewNumbers += aFewNumbers[i] * aFewNumbers[i];
}

If you can use ES6, you can even use higher-order array functions to simplify this more:

var squareOfAFewNumbers = aFewNumbers.reduce((result, entry) => result + entry * entry, 0);

You can use JavaScript pow() Method to create the square and sum it to the sumSquareOfAFewNumbers .

 var aFewNumbers = [ 1, 2, 3, 7 ]; var sumSquareOfAFewNumbers = 0; aFewNumbers.forEach(function(element) { sumSquareOfAFewNumbers += Math.pow(element, 2); }); console.log(sumSquareOfAFewNumbers)

There are multiple approaches you can take for reaching the desired result, but as you've mentioned that you must write a for loop; therefore, I sorted the answers by having that in mind.

Using the for loop

let numbers = [1, 2, 3, 7],
    sum = 0;

for(let i = 0; i < numbers.length; i++) {
    sum += Math.pow(numbers[i], 2)
}

// Sum is now 63

Using forEach method of the array object

let numbers = [1, 2, 3, 7],
    sum = 0;

numbers.forEach(number => sum += Math.pow(number, 2))

// Sum is now 63

Oneliner

let sum = [1, 2, 3, 7].reduce((a, c) => a + Math.pow(c, 2))

The reduce method uses an accumulator to store temporary results, the accumulator is passed to the callback as the first argument and the second argument is the element's value, you can read more about the reduce method here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM