LeetCode 题解工作台

返回传递的参数的长度

请你编写一个函数 argumentsLength ,返回传递给该函数的参数数量。 示例 1: 输入: args = [5] 输出: 1 解释: argumentsLength(5); // 1 只传递了一个值给函数,因此它应返回 1。 示例 2: 输入: args = [{}, null, "3"]…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · Return Length of Arguments Passed core interview pattern

bolt

答案摘要

function argumentsLength(...args: any[]): number { return args.length;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Return Length of Arguments Passed core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你编写一个函数 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
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
function argumentsLength(...args: any[]): number {
    return args.length;
}

/**
 * argumentsLength(1, 2, 3); // 3
 */
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

返回传递的参数的长度题解:Return Length of Argume… | LeetCode #2703 简单