admin管理员组文章数量:1244386
In PHP we can specify default value of variable in function like:
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.
}
Is there something similar to this in JavaScript?
In PHP we can specify default value of variable in function like:
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.
}
Is there something similar to this in JavaScript?
Share Improve this question asked Sep 7, 2010 at 7:24 tomsseisumstomsseisums 13.4k20 gold badges88 silver badges148 bronze badges3 Answers
Reset to default 9You don't need to pass all the variables in Javascript.
Although a less hacky way would be to use objects:
function foo(args) {
var text = args.text || 'Bar';
alert(text);
}
To call it:
foo({ text: 'Hello' }); // will alert "Hello"
foo(); // will alert "Bar" as it was assigned if args.text was null
not exactly, but you can simulate it by checking if a value was passed and setting a default, e.g.
optionalArg = (typeof optionalArg == "undefined")?'defaultValue':optionalArg
Note that technique like this works even when optionalArg is supplied but evaluates as false - something that a simpler idiom like optionalArg=optionalArg || 'default'
fails on.
Also inside every function you can access to an array called arguments which will contain all the arguments passed to the function, you can use that to have functions with variable length argument lists.
None that I'm aware of:
But there are 2 ways to tackle this.
//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"
本文标签: javascriptFunction required and notrequired variablesStack Overflow
版权声明:本文标题:javascript - Function required and not-required variables - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740223113a2244192.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论