
javascript、方法重载(如 java 或 c# 等语言中的方法重载)不受直接支持,因为函数只能有一个定义。然而,javascript 是动态的,允许我们使用以下技术来模拟重载:
检查参数数量或类型。
使用默认参数。
使用参数或剩余参数。
以下是一些实现重载行为的方法。
1. 使用参数对象
`function add() {
if (arguments.length === 1) {
return arguments[0]; // single argument
} else if (arguments.length === 2) {
return arguments[0] + arguments[1]; // two arguments
}
}
console.log(add(5)); // 5
console.log(add(5, 10)); // 15`
arguments 是一个类似数组的对象,保存传递给函数的所有参数。
根据参数的数量,我们执行不同的逻辑。
2. 类型检查重载
`function greet(name) {
if (typeof name === "string") {
console.log(`Hello, ${name}!`);
} else if (Array.isArray(name)) {
console.log(`Hello, ${name.join(", ")}!`);
}
}
greet("Alice"); // Hello, Alice!
greet(["Alice", "Bob"]); // Hello, Alice, Bob!`











