在PHP中,我们可以在函数中指定变量的默认值,如:
function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){
// so yeah, myDefaultVariable is required always,
// same applies for myOtherVariable,
// and myCheckVariable can be skipped in function call, because it has a default value already specified.
}
JavaScript中有类似的内容吗?
答案 0 :(得分:9)
您无需在Javascript中传递所有变量。
虽然使用对象的方法不那么简单:
function foo(args) {
var text = args.text || 'Bar';
alert(text);
}
要打电话:
foo({ text: 'Hello' }); // will alert "Hello"
foo(); // will alert "Bar" as it was assigned if args.text was null
答案 1 :(得分:4)
不完全正确,但您可以通过检查是否传递了值并设置默认值来模拟它,例如
optionalArg = (typeof optionalArg == "undefined")?'defaultValue':optionalArg
请注意,这样的技术即使在提供了OptionalArg但是评估为false时也能正常工作 - 这就像optionalArg=optionalArg || 'default'
这样的简单习惯用法失败了。
同样在每个函数内部,您可以访问名为arguments的数组,该数组将包含传递给函数的所有参数,您可以使用它来使函数具有可变长度参数列表。
答案 2 :(得分:1)
我没有意识到:
但有两种方法可以解决这个问题。
//1. function.arguments - this is advisable if you don't know the
// maximum number of passed arguments.
function foo() {
var argv = foo.arguments;
var argc = argv.length;
for (var i = 0; i < argc; i++) {
alert("Argument " + i + " = " + argv[i]);
}
}
foo('hello', 'world');
//2. "Or" operator - this is good for functions where you know the
// details of the optional variable(s).
function foo (word1, word2) {
word2 = word2 || 'world';
alert (word1 + ' ' + word2);
}
foo ('hello'); // Alerts "hello world"