用js实现一个加法的方法
/**
* Adds two numbers together.
*
* @param {number} a The first number.
* @param {number} b The second number.
* @returns {number} The sum of the two numbers.
*/
function add(a, b) {
return a + b;
}
// Examples:
console.log(add(2, 3)); // Output: 5
console.log(add(-1, 1)); // Output: 0
console.log(add(0.1, 0.2)); // Output: 0.30000000000000004 (due to floating-point precision)
// Handling potential errors: More robust version
/**
* Adds two numbers together, handling non-numeric inputs.
*
* @param {number} a The first number.
* @param {number} b The second number.
* @returns {number | string} The sum of the two numbers, or an error message if inputs are invalid.
*/
function addSafe(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
return "Invalid input: Both arguments must be numbers.";
}
return a + b;
}
console.log(addSafe(2, 3)); // Output: 5
console.log(addSafe("hello", 3)); // Output: "Invalid input: Both arguments must be numbers."
// Even more robust, handling NaN:
/**
* Adds two numbers together, handling non-numeric inputs and NaN.
*
* @param {number} a The first number.
* @param {number} b The second number.
* @returns {number | string} The sum of the two numbers, or an error message if inputs are invalid or result in NaN.
*/
function addRobust(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
return "Invalid input: Both arguments must be numbers.";
}
const sum = a + b;
if (isNaN(sum)) {
return "Error: Result is NaN.";
}
return sum;
}
console.log(addRobust(2, 3)); // Output: 5
console.log(addRobust(Infinity, -Infinity)); // Output: "Error: Result is NaN."
I've provided three versions:
-
add(a, b)
: A simple and straightforward addition function. It's efficient but doesn't handle invalid input. -
addSafe(a, b)
: A safer version that checks if the inputs are numbers and returns an error message if they aren't. This prevents unexpected behavior. -
addRobust(a, b)
: The most robust version. It handles non-numeric inputs and checks forNaN
(Not a Number) results, which can occur in certain calculations (like Infinity - Infinity). This provides the most comprehensive error handling.
Choose the version that best suits your needs in terms of simplicity and error handling. For most common cases, addSafe
is a good balance. If you anticipate potentially problematic inputs, addRobust
is the best choice.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律