js 实现加法
基本加法实现
在JavaScript中实现加法可以直接使用+运算符。这是最基础的方法:
let sum = 1 + 2; // 结果为3
函数封装加法
通过函数封装可以提升代码复用性:
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 输出8
处理多参数相加
使用剩余参数处理不定数量的加数:
function multiAdd(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(multiAdd(1, 2, 3, 4)); // 输出10
类型安全加法
添加类型检查防止非数字相加:
function safeAdd(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('参数必须为数字');
}
return a + b;
}
大数相加处理
处理超出安全整数范围的加法:
function bigIntAdd(a, b) {
return BigInt(a) + BigInt(b);
}
console.log(bigIntAdd('9007199254740992', '1')); // 输出9007199254740993n
浮点数精度处理
解决浮点数计算精度问题:
function floatAdd(a, b) {
const factor = Math.pow(10, Math.max(a.toString().split('.')[1]?.length || 0,
b.toString().split('.')[1]?.length || 0));
return (a * factor + b * factor) / factor;
}
console.log(floatAdd(0.1, 0.2)); // 输出0.3
链式加法实现
支持链式调用的加法器:
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this;
}
}
new Calculator(5).add(3).add(2); // 最终value为10






