Home > Article > Web Front-end > How to calculate the product from 1 to 10 in javascript
In JavaScript, you can use the for loop statement and the "*" operator to calculate the product from 1 to 10. The syntax format is "var cj=1;for(var i=1;i
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript calculates the product from 1 to 10
Use a for loop to traverse the numbers from 1 to 10 and multiply them to obtain The product of 1 to 10.
for (var i = 1; i <= 10; i++) { cj *= i; //或 //cj = cj * i; }
The variable cj is used to obtain the final product value. In order not to affect the result when defining, it needs to be initialized and assigned the value 1
.
var cj=1;
The variable cj is defined before the for loop.
The complete implementation code is given below:
var cj = 1; for (var i = 1; i <= 10; i++) { cj = cj * i; } console.log("1到10的乘积为:" + cj);
Encapsulated into a function:
function cj(n) { var cj=1; for (var i=1;i<=n;i++){ cj *= i; } return cj; } console.log("1到10的乘积为:"+cj(10));
[Related recommendations: javascript learning Tutorial】
The above is the detailed content of How to calculate the product from 1 to 10 in javascript. For more information, please follow other related articles on the PHP Chinese website!