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

How to calculate the product from 1 to 10 in javascript

青灯夜游
Release: 2022-01-23 18:09:51
Original
3765 people have browsed it

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;
}
Copy after login

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;
Copy after login

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);
Copy after login

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));
Copy after login

[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!

Related labels:
source:php.cn
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