Program Tip

Javascript 함수에서 매개 변수를 전달하지 않으면 어떻게됩니까?

programtip 2020. 10. 19. 12:38
반응형

Javascript 함수에서 매개 변수를 전달하지 않으면 어떻게됩니까?


저는 Javascript의 세계에 익숙하지 않고 매우 기본적인 기능을 작성하는 데 익숙해지고 실수로 아래 예제를 우연히 발견했으며 함수가 요구할 때 매개 변수를 전달하지 않을 때 왜 작동하는지 확신 할 수 없습니다.

샘플 기능

function myfunction(x) {
    alert("This is a sample alert");
}

이제 함수를 호출 myfunction();하면 경고가 표시됩니다. 매개 변수를 전달하지 않았는데도 오류나 경고없이 함수를 호출 할 수있는 이유는 무엇입니까?

편집하다

나는 그렇게 많은 훌륭한 답변을 기대하지 않았고 나는 결코 어떤 대답이 가장 좋은지 말할 수있는 위치에 있지 않기 때문에 사람들에게 베스트 답변을 제안하도록 요청할 수 있고 그 사람에게 수락을 줄 것입니다.


아무 일도 일어나지 않습니다. 즉, 자바 스크립트에서 매개 변수를 전달하는 것은 선택 사항이므로 오류나 경고가 표시되지 않습니다.
"제공"되지 않은 모든 매개 변수는 undefined 을 갖습니다 .

function foo(x, y, z){
    //...
}

foo(1);

foo이제 함수 내부 :

function foo(x, y, z){
    x === 1
    y === undefined
    z === undefined
}

다음과 같이 더 많은 인수를 전달할 수도 있습니다.

foo(1,2,3,4,5,7); // Valid!

arguments.length함수 내부에서에서 제공하는 매개 변수의 양을 알 수 있습니다 .

function foo(x, y, z) {
    console.log('x value: ' + x);
    console.log('y value: ' + y);
    console.log('z value: ' + z);
    console.log('Arguments length: ' + arguments.length);
}
console.log('Zero parameters');
foo();
console.log('Four parameters');
foo(1, 2, 3, 4);

모든 양의 매개 변수를 처리하는 유용한 함수의 예 :

function max() {
    var maxValue = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        if (maxValue < arguments[i]) {
            maxValue = arguments[i];
        }
    }
    return maxValue;
}

alert(max(1, 5, 7, 2, 88, 32, 44));


JavaScript 함수의 모든 인수는 선택 사항입니다 ( "느슨하게 입력 된"읽기).

JavaScript 함수는 함수 정의에 이름이 지정된 인수의 수에 관계없이 여러 인수로 호출 할 수 있습니다. 함수는 형식이 느슨하기 때문에 예상되는 인수 유형을 선언 할 방법이 없으며 모든 유형의 값을 모든 함수에 전달할 수 있습니다. 선언 된 것보다 적은 인수로 함수를 호출하면 추가 인수는 정의되지 않은 값을 갖습니다.

명명 된 인수 변수 또는 arguments 객체를 사용하여 함수 내에서 함수의 인수를 참조 할 수 있습니다. 이 객체는 함수에 전달 된 각 인수에 대한 항목을 포함합니다. 첫 번째 항목의 인덱스는 0에서 시작합니다. 예를 들어 함수에 세 개의 인수가 전달되면 다음과 같이 인수를 참조 할 수 있습니다.

arguments[0]
arguments[1]
arguments[2]
  • JavaScript-The Definitive Guide, 5th Edition

이것이 바로 JavaScript가 작동하는 방식입니다. 매개 변수는 선택 사항이며, 함수 호출에서 누락 된 경우 함수에 "정의되지 않은"값이 아닌 값을 갖습니다.

"선택 사항"이란 단지 의미합니다. 함수를 호출 하는 데는 임의로 긴 매개 변수 목록이 포함됩니다. 함수에 전달 된 매개 변수 의 수와 선언 된 수 사이에는 관계가 없어야 합니다. 이 선언을 생각하는 가장 좋은 방법은 다음과 같습니다.

function x(a, b, c) {
  // ...
}

is that you're declaring a function and binding the name "a" to the first parameter, "b" to the second, and "c" to the third. It's by no means guaranteed, however, that any of those will actually be bound to a value in any given invocation of the function later.

By the same token, you can define a function without any parameters at all, and then "find" them via the arguments object:

function noArgs() {
  var a = arguments[0], b = arguments[1], c = arguments[2];
  // ...
}

So that's not quite the same as the first function, but it's close in most ways that count practically.

The "undefined" value in JavaScript is a value, but it's semantics are kind-of unusual as languages go. In particular it's not exactly the same as the null value. Also, "undefined" itself is not a keyword; it's just a semi-special variable name!


JavaScript doesn't have default values for function parameters like other languages do. So, you can pass as many or as little arguments as you want.

If you don't pass a value, the parameter is undefined.

function myfunction(x) {
    alert(x);
}

myfunction(); // alerts undefined
myfunction(1); // alerts 1
myfunction(1,2,3); // alerts 1

If you pass more parameters than are in the signature, you can use arguments.

function myfunction(x) {
    alert(x);
    console.log(arguments);
}

myfunction(1,2,3); // alerts 1, logs [1,2,3]

You can also provide more arguments than just the one mentioned in the function

myFunction(1,2,3,4,5,6,7,'etc');

You can use the arguments property which is an array in order to view the provided arguments.


Because there's no error until the function expects to be able to work with the parameter that you're supposed to pass.

For example:

function myfunction(x) {
    return x*2;
}

Would throw an error; albeit probably only a NaN (in this case) or a variable is undefined.


If you omit the argument, its value will be undefined. This enables you to create optional parameters quite easily.

Another feature is the ability to define a function with no parameters, and call it with arguments successfully, making use of the arguments object. This lets you easily create variable-length argument arrays.

참고URL : https://stackoverflow.com/questions/11107823/what-happens-if-i-dont-pass-a-parameter-in-a-javascript-function

반응형