如果我不在Javascript函数中传递参数会发生什么? [英] What happens if I don't pass a parameter in a Javascript function?
问题描述
我是Javascript世界的新手,并且正在修改编写非常基本的函数,并偶然发现了下面的示例,并且当函数需要时我不传递参数时,我不确定它为什么会起作用。
示例函数
function myfunction(x){
alert(这是一个示例警报);
}
现在如果我调用函数 myfunction();
我收到警报。为什么我没有传递参数时能够在没有任何错误或警告的情况下调用该函数?
编辑
我没想到会有这么多很棒的答案,我绝不能说明哪个答案最好,所以我可以请求别人提出最佳答案我会将接受授予该人。
什么都不会发生 - 意味着您不会收到错误或警告,因为在javascript中传递参数是可选的。< br>
所有未提供的参数都将包含 undefined
value 。
function foo(x,y ,z){
// ... ...
}
foo(1);
现在在 foo
函数内:
function foo(x,y,z){
x === 1
y === undefined
z === undefined
}
您甚至可以传递更多参数,例如: / p>
foo(1,2,3,4,5,7); //有效!
您可以知道 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) ;
处理任意数量参数的有用函数示例: / p>
function max(){var maxValue = arguments [0]; for(var i = 1; i< arguments.length; i ++){if(maxValue< arguments [i]){maxValue = arguments [i];返回maxValue;} alert(max(1,5,7,2,88,32,44));
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.
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?
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.
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 undefined
value.
function foo(x, y, z){
//...
}
foo(1);
Inside the foo
function now:
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.length
from inside the function.
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));
这篇关于如果我不在Javascript函数中传递参数会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!