js 实现加法
基本加法实现
在JavaScript中实现加法可以通过简单的+运算符完成。例如:
let sum = 1 + 2; // 结果为3
函数封装加法
为复用逻辑可封装为函数:

function add(a, b) {
return a + b;
}
console.log(add(3, 5)); // 输出8
处理浮点数精度
直接相加可能导致浮点数精度问题,需特殊处理:

function safeAdd(a, b) {
const factor = Math.pow(10, Math.max(getDecimalLength(a), getDecimalLength(b)));
return (a * factor + b * factor) / factor;
}
function getDecimalLength(num) {
return (num.toString().split('.')[1] || '').length;
}
console.log(safeAdd(0.1, 0.2)); // 正确输出0.3
多参数相加
通过扩展运算符支持任意数量参数:
function multiAdd(...numbers) {
return numbers.reduce((acc, cur) => acc + cur, 0);
}
console.log(multiAdd(1, 2, 3, 4)); // 输出10
类型安全加法
添加类型检查避免非数字相加:
function typeSafeAdd(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('Arguments must be numbers');
}
return a + b;
}






