Home  >  Article  >  Web Front-end  >  How to calculate the product from 1 to 10 in javascript

How to calculate the product from 1 to 10 in javascript

青灯夜游
青灯夜游Original
2022-01-23 18:09:513659browse

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

How to calculate the product from 1 to 10 in javascript

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);

How to calculate the product from 1 to 10 in javascript

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!

Statement:
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