JavaScript 不直接支持方法重载(如 Java 或 C# 等语言),因为函数只能有一个定义。然而,JavaScript 是动态的,允许我们使用以下技术来模拟重载:
检查参数数量或类型。
使用默认参数。
使用参数或剩余参数。
下面是一些实现重载行为的方法。
`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 是一个类似数组的对象,保存传递给函数的所有参数。
根据参数的数量,我们执行不同的逻辑。
`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!`
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3