Home > Web Front-end > Front-end Q&A > How to implement square addition in javascript

How to implement square addition in javascript

PHPz
Release: 2023-04-25 13:41:59
Original
907 people have browsed it

In programming languages, the addition of squares is also called the sum of squares. In fact, it is the sum of the squares of each number in a set of numbers. The final result is the sum of the squares of the set of numbers.

In JavaScript, the following methods can be used to implement square addition:

Method 1: Use a for loop

Use a for loop to traverse each element in the array, Just add the squares of each element.

The implementation code is as follows:

function squareSum(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i] * arr[i];
  }
  return sum;
}

let arr = [1, 2, 3, 4, 5];
console.log(squareSum(arr));   //输出55
Copy after login

Method 2: Use Array.reduce()

Use the reduce() method to accumulate each element in the array, and at the same time Just do the squaring operation.

The implementation code is as follows:

function squareSum(arr) {
  let sum = arr.reduce(function(prev, curr) {
    return prev + curr * curr;
  }, 0);
  return sum;
}

let arr = [1, 2, 3, 4, 5];
console.log(squareSum(arr));   //输出55
Copy after login

Method 3: Use map() and reduce() in ES6

The map() method in ES6 can map each element in the array Operate on elements, square each element, and then use the reduce() method to accumulate.

The implementation code is as follows:

function squareSum(arr) {
  let sum = arr.map(function(num) {
    return num * num;
  }).reduce(function(prev, curr) {
    return prev + curr;
  });
  return sum;
}

let arr = [1, 2, 3, 4, 5];
console.log(squareSum(arr));   //输出55
Copy after login

In summary, the above three methods can all implement square addition operations, and you can choose according to your own needs in actual applications.

The above is the detailed content of How to implement square addition in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template