In this tutorial, we'll be discussing how to get the sum of the powers of all the numbers from start to end in JavaScript. We'll be using the built-in Math.pow() method to calculate the powers and the Array reduce() method to sum up the values.
The Math .pow() method allows us to calculate the power of a number. We can use this method to calculate the powers of all the numbers from start to end.
Math.pow(base, exponent) ;
#Base − 基數。
Exponents − 要將基底數提高到的指數。
<html> <head> <title>Examples</title> </head> <body> <div id="result"></div> <script> var sum = 0; for(var i=1; i<=4; i++) { sum += Math.pow(i, 2); } document.getElementById("result").innerHTML = sum; </script> </body> </html>
<html> <head> <title>Example: Using the Array.reduce() method </title> </head> <body> <div id="result"></div> <script> var numbers = [1, 2, 3, 4]; var sum = numbers.reduce(function(a, b) { return a + Math.pow(b, 3); }, 0); document.getElementById("result").innerHTML = sum; </script> </body> </html>
<html> <head> <title>Example: Using the ES6 arrow function</title> </head> <body> <div id="result"></div> <script> var numbers = [1, 2, 3, 4]; var sum = numbers.reduce((a, b) => a + Math.pow(b, 2), 0); document.getElementById("result").innerHTML = sum </script> </body> </html>
以上是如何在JavaScript中取得所有數字的冪的和?的詳細內容。更多資訊請關注PHP中文網其他相關文章!