js实现加减
JavaScript 实现加减运算
在 JavaScript 中,加减运算可以通过基本的算术运算符或函数实现。以下是几种常见的方法:
基本算术运算符
使用 + 和 - 运算符直接进行加减运算:
let a = 5;
let b = 3;
let sum = a + b; // 加法,结果为 8
let difference = a - b; // 减法,结果为 2
函数封装
将加减运算封装为函数,便于复用:
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
let resultAdd = add(10, 5); // 15
let resultSubtract = subtract(10, 5); // 5
动态计算表达式
使用 eval 动态计算字符串表达式(需注意安全性风险):
let expression = "7 + 3";
let result = eval(expression); // 10
对象方法
通过对象方法实现加减运算:
let calculator = {
add: function(x, y) {
return x + y;
},
subtract: function(x, y) {
return x - y;
}
};
let sumResult = calculator.add(4, 2); // 6
let subResult = calculator.subtract(4, 2); // 2
处理浮点数精度问题
JavaScript 的浮点数运算可能存在精度问题,可通过以下方式解决:
function addFloat(x, y) {
return parseFloat((x + y).toFixed(10));
}
function subtractFloat(x, y) {
return parseFloat((x - y).toFixed(10));
}
let floatSum = addFloat(0.1, 0.2); // 0.3
let floatSub = subtractFloat(0.3, 0.1); // 0.2
使用 ES6 箭头函数
简化函数定义:

const add = (x, y) => x + y;
const subtract = (x, y) => x - y;
let arrowSum = add(8, 2); // 10
let arrowSub = subtract(8, 2); // 6
根据具体需求选择合适的方法,基本运算符适用于简单场景,而函数封装或对象方法更适合复杂逻辑。






