Home > Article > Web Front-end > How to find the area of a circle in JavaScript
JavaScript method to find the area of a circle: 1. Find the area of a circle through "function Area(){return(3.14*this.r*this.r)}"; 2. Through "return r*r*" Math.PI" and other methods to find the area of a circle.
The operating environment of this article: Windows 7 system, javascript version 1.8.5, DELL G3 computer
How to find the area of a circle with JavaScript?
JS function to find the area of a circle Summary
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JS 函数</title> <script type="text/javascript" src="jquery-3.1.0.min.js"></script> </head> <body> <script type="text/javascript">
//1. function circle(r) { this.r=r this.Area=Area this.Circum=Circum } function Circum() { return(3.14*2*this.r) } function Area() { return(3.14*this.r*this.r) } r=parseInt(prompt("请输入半径:"," ")); // parseInt() 函数可解析一个字符串,并返回一个整数 var newcircle=new circle(r); var Circumcapital=newcircle.Circum(); var Areacapital=newcircle.Area(); document.write("周长:"+Circumcapital+";"); document.write("面积:"+Areacapital+" ");
//2. var area_of_circle = new Function("r","return r*r*Math.PI"); //创建一个函数对象 var rCircle1 = 2;//给定圆的半径 var area = area_of_circle(rCircle1); alert("半径为2的圆面积为:" + area); var rCircle2 = 3;//给定圆的半径 var area = area_of_circle(rCircle2); alert("半径为3的圆面积为:" + area);
//3. var r=prompt("输入圆的半径","请输入半径:");//prompt() 方法用于显示可提示用户进行输入的对话框 if(r!=null) {undefined var square=r*r*Math.PI; document.write("圆的面积为:"+square); } else {undefined alert("输入数据有误"); } </script> </body> </html>
1., 2. and 3. Three different methods to find the area of a circle. The first method adds the perimeter Calculation method. In the second method, I defined a public function for area_of_circle (area). No matter what the radius is, the area function can be called, which saves the duplication of the function to find the area. The third method pays attention to the prompt() function. The third one has an if judgment to determine whether the input is invalid
Recommended study: "js Basic Tutorial"
The above is the detailed content of How to find the area of a circle in JavaScript. For more information, please follow other related articles on the PHP Chinese website!