如果我不在 Javascript 函数中传递参数会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11107823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:29:28  来源:igfitidea点击:

What happens if I don't pass a parameter in a Javascript function?

javascriptoverloading

提问by PeanutsMonkey

I am new to the world of Javascript and am tinkering with writing very basic functions and stumbled upon the example below by accident and am unsure why it works when I am not passing a parameter when the function demands it.

我是 Javascript 世界的新手,正在修补编写非常基本的函数,偶然发现了下面的示例,我不确定为什么在函数需要时我没有传递参数时它会起作用。

Sample function

示例函数

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

Now if I call the function myfunction();I am presented with the alert. Why is that that I am able to call the function without any errors or warnings when I have not passed a parameter?

现在,如果我调用该函数,则会myfunction();收到警报。为什么我可以在没有传递参数的情况下调用函数而没有任何错误或警告?

EDIT

编辑

I did not expect so many great answers and I am by no means in a position yet able to say which answer is the best so am I able to request people to suggest the best answer and I'll award the acceptance to that person.

我没想到会有这么多很棒的答案,而且我绝对无法说出哪个答案是最好的,所以我可以要求人们提出最佳答案,然后我将接受该人。

回答by gdoron is supporting Monica

Nothing will happen- meaning you won't get an error or a warning as passing the parameters in javascript is optional.
All the parameters that weren't "supplied" will have the undefinedvalue.

什么都不会发生 - 这意味着您不会收到错误或警告,因为在 javascript 中传递参数是可选的。
所有未“提供”的参数都将具有undefined.

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

foo(1);

Inside the foofunction now:

foo现在在函数内部:

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

You can even pass more arguments, like:

您甚至可以传递更多参数,例如:

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

You can know the amounts of parameters supplied by arguments.lengthfrom inside the function.

您可以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);

Example of useful function that handle any amount of parameters:

处理任意数量参数的有用函数示例:

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));

回答by j08691

All arguments in JavaScript functions are optional (read "loosely typed").

JavaScript 函数中的所有参数都是可选的(读作“松散类型”)。

JavaScript functions can be invoked with any number of arguments, regardless of the number of arguments named in the function definition. Because a function is loosely typed, there is no way for it to declare the type of arguments it expects, and it is legal to pass values of any type to any function. When a function is invoked with fewer arguments than are declared, the additional arguments have the undefined value.

可以使用任意数量的参数调用 JavaScript 函数,而不管函数定义中命名的参数数量如何。因为函数是松散类型的,所以它无法声明它期望的参数类型,并且将任何类型的值传递给任何函数都是合法的。当一个函数被调用的参数少于声明的参数时,额外的参数具有未定义的值。

You can refer to a function's arguments within the function by using the named argument variables or the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as follows:

您可以使用命名参数变量或参数对象在函数内引用函数的参数。此对象包含传递给函数的每个参数的条目,第一个条目的索引从 0 开始。例如,如果一个函数传递了三个参数,则可以按如下方式引用该参数:

arguments[0]
arguments[1]
arguments[2]
  • JavaScript - The Definitive Guide, 5th Edition
  • JavaScript - 权威指南,第 5 版

回答by Pointy

That's just how JavaScript works. Parameters are optional, and will have the not-really-a-value value "undefined" in the function if they're missing from a function call.

这就是 JavaScript 的工作方式。参数是可选的,如果函数调用中缺少它们,则函数中将具有非真正值“未定义”的值。

By "optional" I mean just that: invoking anyfunction involves an arbitrarily long list of parameters. There need be no relationship between the number of parameters passedto a function and the number declared. Best way to think of this declaration, then:

“可选”我的意思是:调用任何函数都涉及任意长的参数列表。传递给函数的参数数量和声明的数量之间不需要有任何关系。考虑此声明的最佳方式,然后:

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 actuallybe bound to a value in any given invocation of the function later.

是您声明了一个函数并将名称“a”绑定到第一个参数,将“b”绑定到第二个参数,将“c”绑定到第三个参数。然而,这绝不是保证,在任何给定的函数调用中,这些中的任何一个实际上都会绑定到一个值。

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

出于同样的原因,您可以定义一个完全不带任何参数的函数,然后通过arguments对象“找到”它们:

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

So that's not quitethe 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 nullvalue. Also, "undefined" itself is not a keyword; it's just a semi-special variable name!

JavaScript 中的“未定义”值是一个值,但随着语言的发展,它的语义有点不寻常。特别是它与null值不完全相同。此外,“未定义”本身不是关键字;它只是一个半特殊的变量名!

回答by Rocket Hazmat

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.

JavaScript 不像其他语言那样有函数参数的默认值。因此,您可以根据需要传递尽可能多或尽可能少的参数。

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

如果不传递值,则参数为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.

如果传递的参数多于签名中的参数,则可以使用arguments.

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

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

回答by AlbertVanHalen

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 argumentsproperty which is an array in order to view the provided arguments.

您可以使用arguments数组属性来查看提供的参数。

回答by David says reinstate Monica

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.

会抛出错误;尽管可能只有一个NaN(在这种情况下)或一个variable is undefined.

回答by Kendall Frey

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

如果省略该参数,则其值为undefined。这使您可以非常轻松地创建可选参数。

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

另一个特性是能够定义一个没有参数的函数,并成功地调用它,利用arguments对象。这使您可以轻松创建可变长度的参数数组。

回答by Goyal Vicky

In javascript console.log inside a function gives undefined as output for unpassed parameters but outside the function it gives not defined error as inside a function browsers explicitly declares the variable. For e.g

在 javascript console.log 中,函数内部为未传递的参数提供 undefined 作为输出,但在函数外部它给出未定义的错误,因为在函数内部浏览器显式声明了变量。例如

console.log(x) 

gives VM1533:1 Uncaught ReferenceError: x is not defined whereas

给出 VM1533:1 Uncaught ReferenceError: x is not defined 而

function test(x) {
console.log(x)
}
test(); 

gives undefined. It is because the function test() is rewritten by browser as:

给出未定义。这是因为函数 test() 被浏览器重写为:

function test(x) {
    var x;
    console.log(x)
    }

Another Example : -

另一个例子 : -

var x =5 ;
function test(x) {
console.log(x)
}
test(); 

is still undefined as the function becomes

随着函数变为未定义

function test(x) {
    var x;
    console.log(x)
    }

The alert in the below example will give undefined :-

以下示例中的警报将给出 undefined :-

    var x =5;
    function test() {
    alert(x);
    var x =10;
    }

test(); 

The above function will become :-

上述功能将变为:-

 function test() {
    var x;
    alert(x);
    x =10;
    }

The scope of javascript variable inside a function is function level scope and not block level. For e.g.

函数内 javascript 变量的作用域是函数级作用域而不是块级作用域。例如

function varScope() {

for(var i = 0; i < 10; i++){
    for(var j = 0; j < 5; j++){}
        console.log("j is "+j)
    }
    console.log("i is "+i);


}
varScope();

will give output as :

将输出为:

j is 5 
i is 10

Again the function has become as :-

功能再次变为:-

  function varScope() {
    var i;
    var j;
    for(i = 0; i < 10; i++){
        for(j = 0; j < 5; j++){}
            console.log("j is "+j)
        }
        console.log("i is "+i);
    }