在某些语言中,您可以为函数的参数设置默认值:
function Foo(arg1 = 50, arg2 = 'default') {
//...
}
Run Code Online (Sandbox Code Playgroud)
你是如何用JavaScript做的?
创建一个在nodejs中接受可选参数的函数的最佳方法是什么?
例如,我知道这种方法: -
function optionalArguments(a,b){
var a = a || "nothing";
var b = b || "nothing";
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,如果我这样做:
optionalArguments(FALSE,FALSE)
虽然我已经通过了一个论证,但是a和b都返回"没有".
当我调用这样的函数时,我也得到意外的令牌错误:
optionalArguments( "XXX");
是否有更好的或标准的方法来处理nodejs中的可选参数?
任何帮助表示赞赏.提前致谢.
我需要一个函数,它的参数是一个对象,如果我将其保留为空,它将加载默认值。
就像是:
function loadMap(args) { //args is an object and its optional
//this is what I want to do, test args and load defauts if necesary
/*
pseudocode:
if args.latitude is not set then
give it a default value
if args.longitude is not set then
give it a default value
end pseudocode */
alert("Latitude is "+args.latitude );
alert("Longitude is "+args.longitude );
}
//outputs the default values
loadMap();
//outputs custom values
loadMap({latitude: "x.xxxx", longitude: "-x.xxxx"});
//and should work too and output …Run Code Online (Sandbox Code Playgroud) 假设我有这个:
function concatenate(a, b, c) {
// Concatenate a, b, and c
}
Run Code Online (Sandbox Code Playgroud)
我该如何处理这些电话?
x = concatenate(a)
x = concatenate(a, b)
x = concatenate(a, c)
Run Code Online (Sandbox Code Playgroud)
如何让我的函数知道我给它的参数?
我想编写一个使用参数值的函数.如果参数不存在,默认情况下将使用值true.
var check = function(truthValue){
var val = truthValue || true;
console.log(val);
};
Run Code Online (Sandbox Code Playgroud)
问题是,如果我将值false传递给它,因为它仍将使用默认值.那么如何检查varible是否存在并在Javascript中使用该值?
在JavaScript中,您可以创建如下函数:
function Cat(children) {
this.children = children || 3;
}
Run Code Online (Sandbox Code Playgroud)
它的作用是它创建一个Cat带有children值的对象,如果你不传递children函数内部var mimmi = new Cat();,它将是相同的var mimmi = new Cat(undefined);,这意味着它mimmi的默认children值为3.
但是,唯一的问题是,如果我输入0,它将被计数为,false并且children将被设置为3,当我实际想要将其设置为时0.
制作这样的功能最优雅的方法是什么,但仍允许0?
我不认为这看起来很好看:
function Cat(children) {
this.children = (typeof this.children == "number") ? children : 3
}
Run Code Online (Sandbox Code Playgroud)