LeetCode 题解工作台
返回传递的参数的长度
请你编写一个函数 argumentsLength ,返回传递给该函数的参数数量。 示例 1: 输入: args = [5] 输出: 1 解释: argumentsLength(5); // 1 只传递了一个值给函数,因此它应返回 1。 示例 2: 输入: args = [{}, null, "3"]…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Return Length of Arguments Passed core interview pattern
答案摘要
function argumentsLength(...args: any[]): number { return args.length;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Return Length of Arguments Passed core interview pattern 题型思路
题目描述
argumentsLength,返回传递给该函数的参数数量。
示例 1:
输入:args = [5] 输出:1 解释: argumentsLength(5); // 1 只传递了一个值给函数,因此它应返回 1。
示例 2:
输入:args = [{}, null, "3"]
输出:3
解释:
argumentsLength({}, null, "3"); // 3
传递了三个值给函数,因此它应返回 3。
提示:
args是一个有效的 JSON 数组0 <= args.length <= 100
解题思路
方法一
function argumentsLength(...args: any[]): number {
return args.length;
}
/**
* argumentsLength(1, 2, 3); // 3
*/
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) since counting the number of arguments is immediate. Space complexity is O(1) when using the arguments object or rest parameters, and O(n) if copying arguments into a new array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Wants to see understanding of variable-length argument handling.
- question_mark
Checks if candidate avoids off-by-one mistakes in counting.
- question_mark
Observes whether both empty and mixed-type calls are correctly handled.
常见陷阱
外企场景- error
Assuming a fixed number of parameters rather than counting all provided arguments.
- error
Forgetting to handle zero arguments correctly, leading to undefined or errors.
- error
Miscounting when using spread operators or nested arrays instead of flat arguments.
进阶变体
外企场景- arrow_right_alt
Return the types of each argument along with the count for extended type-checking practice.
- arrow_right_alt
Implement the function in a statically typed language where argument count must be inferred.
- arrow_right_alt
Return the number of truthy arguments only, adding a conditional filter to the core counting pattern.