圓面積公式:S = π × r²
Math.PIconst r = 2;
const area = Math.PI * r * r;
console.log(`半徑 ${r} 的圓面積:${area.toFixed(2)}`); // 12.57
function circleArea(radius) {
if (typeof radius !== 'number' || radius < 0) {
throw new Error('半徑必須為非負數字');
}
return Math.PI * radius * radius;
}
console.log(circleArea(2)); // 12.56637...
const circleArea = r => Math.PI * r ** 2;
console.log(circleArea(2));
// 原文代碼
var circularityArea = new Function("r", "return r*r*Math.PI");
var area = circularityArea(2);
缺點:類似 eval,字符串代碼難調試、有安全風險、無法優化、不支持閉包。
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
get circumference() {
return 2 * Math.PI * this.radius;
}
}
const c = new Circle(2);
console.log(c.area); // 12.57
const PI = Math.PI;
const square = x => x * x;
const multiply = a => b => a * b;
const circleArea = r => multiply(PI)(square(r));
// 或組合
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const circleArea2 = compose(multiply(PI), square);
// 保留 2 位小數
area.toFixed(2); // "12.57" (字符串)
Number(area.toFixed(2)); // 12.57 (數字)
// 科學計數法
area.toExponential(2); // "1.26e+1"
// 國際化格式
area.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
const circle = {
area: r => Math.PI * r ** 2,
circumference: r => 2 * Math.PI * r,
diameter: r => 2 * r,
// 扇形面積(角度制)
sectorArea: (r, deg) => Math.PI * r ** 2 * (deg / 360),
// 弧長
arcLength: (r, deg) => 2 * Math.PI * r * (deg / 360)
};
1/2 === 0.5,無需擔心0.1 + 0.2 !== 0.3,貨幣/精密計算用整數(分)或 decimal.jsradius >= 0計算圓面積雖簡單,但承載了從基礎語法到函數式編程、面向對象設計的多種範式。實際開發中推薦 箭頭函數 或 類封裝,兼顧簡潔與擴展性;避免使用 new Function 或 eval 類動態代碼執行方式。