IT이야기

함수의 arity 얻기

cyworld 2021. 10. 17. 09:57
반응형

함수의 arity 얻기


Javascript에서 함수에 대해 정의된 형식 매개변수의 수를 어떻게 결정할 수 있습니까?

이것은 arguments함수가 호출될 때 매개변수 가 아니라 함수가 정의된 명명된 인수의 수입니다.

function zero() {
    // Should return 0
}

function one(x) {
    // Should return 1
}

function two(x, y) {
    // Should return 2
}

> zero.length
0
> one.length
1
> two.length
2

원천

함수는 다음과 같이 고유한 승수(길이)를 결정할 수 있습니다.

// For IE, and ES5 strict mode (named function)
function foo(x, y, z) {
    return foo.length; // Will return 3
}

// Otherwise
function bar(x, y) {
    return arguments.callee.length; // Will return 2
}

함수의 arity는 .length속성에 저장됩니다 .

function zero() {
    return arguments.callee.length;
}

function one(x) {
    return arguments.callee.length;
}

function two(x, y) {
    return arguments.callee.length;
}

> console.log("zero="+zero() + " one="+one() + " two="+two())
zero=0 one=1 two=2

다른 답변에서 다루듯이 length속성에서 알려줍니다. 따라서 zero.length0 one.length이 되고 1 two.length이 되고 2가 됩니다.

ES2015 기준으로 두 가지 주름이 있습니다.

  • 함수는 매개변수 목록의 끝에 "rest" 매개변수를 가질 수 있습니다. 이 매개변수는 해당 위치 또는 이후에 실제 배열( arguments의사 배열 과 다름)에 제공된 모든 인수를 수집합니다.
  • 함수 매개변수는 기본값을 가질 수 있습니다.

The "rest" parameter isn't counted when determining the arity of the function:

function stillOne(a, ...rest) { }
console.log(stillOne.length); // 1

Similarly, a parameter with a default argument doesn't add to the arity, and in fact prevents any others following it from adding to it even if they don't have explicit defaults (they're assumed to have a silent default of undefined):

function oneAgain(a, b = 42) { }
console.log(oneAgain.length);    // 1

function oneYetAgain(a, b = 42, c) { }
console.log(oneYetAgain.length); // 1


A function arity is the number of parameters the function contains.It can be attained by calling the length property.

Example:

function add(num1,num2){}
console.log(add.length); // --> 2

function add(num1,num2,num3){}
console.log(add.length); // --> 3

Note: the number of parameters passed in a function call does not affect the function's arity.


The arity property used to return the number of arguments expected by the function, however, it no longer exists and has been replaced by the Function.prototype.length property.

ReferenceURL : https://stackoverflow.com/questions/4848149/get-a-functions-arity

반응형