[英]Is it required to define parameters in a Javascript function?
是否需要在javascript函数中定义参数? 我的问题是关于我下面的comchoice
函数,我只是使用open和close括号而不提供任何可以更改的参数。
我列出了脚本的完整代码,仅供参考
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var compchoice = function ()
{
if (computerChoice <= 0.34)
{
return computerChoice = "Rock";
}
else if(0.35 <= computerChoice <= 0.67)
{
return computerChoice = "Paper";
}
if (0.68 <= computerChoice <= 1)
{
return computerChoice = "Scissors";
}
};
compchoice();
var compare = function (choice1, choice2)
{
if (choice1 === choice2)
{
return alert("The result is a tie!");
}
if (choice1 === "Rock")
{
if (choice2 === "Scissors")
{
return alert("Rock wins!");
}
else if (choice2 === "Paper")
{
return alert("Paper wins!");
}
}
else if (choice1 === "Scissors")
{
if (choice2 === "Rock")
{
return alert("Rock wins!");
}
else if (choice2 === "Paper")
{
return alert("Schissors wins!");
}
}
};
compare(userChoice, computerChoice);
不,没有必要传递参数,功能可以没有参数。 在你的情况下,函数正在使用闭包访问外部变量。
你可以做的是如下:
function RandomFunction(){
alert( arguments[0] );
console.log( arguments[1] );
}
RandomFunction( 'Hello World', 'Good bye' );
并在函数中的“arguments”变量中查找函数的参数。 因此,不需要声明参数,但声明它们总是一个很好的方法。
此外,您可以传入一个对象作为可扩展的对象列表,而不是使用传统参数:
function AnotherFunction( x ){
alert( x.message );
}
AnotherFunction( {message: 'Hello Again, world'} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.