我总是在JavaScript中处理可选参数,如下所示:
function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';
// Do stuff
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
是否有任何使用||这种情况会失败的情况?
在jQuery的核心风格指南建议两种不同的方法来检查一个变量是否被定义.
typeof variable === "undefined"variable === undefinedobject.prop === undefined为什么jQuery对全局变量使用一种方法而对本地和属性使用另一种方法?
我是来自Python背景的JavaScript的新手.在Python中,参数可以作为键和值传递:
def printinfo( name, age = 35 ):
print "Name: ", name
print "Age ", age
return;
Run Code Online (Sandbox Code Playgroud)
然后可以这样调用该函数:
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Run Code Online (Sandbox Code Playgroud)
这些参数可以在JavaScript函数中传递吗?
我希望能够传递一个或多个参数.例如一个JavaScript函数:
function plotChart(data, xlabel, ylabel, chart_type="l"){
...
}
Run Code Online (Sandbox Code Playgroud)
我希望能够只传递数据和图表类型,标签是可选的,例如:
plotChart(data, chart_type="pie")
Run Code Online (Sandbox Code Playgroud)
这可以用JavaScript吗?
我需要一个函数,它的参数是一个对象,如果我将其保留为空,它将加载默认值。
就像是:
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) javascript ×4
arguments ×1
function ×1
jquery ×1
object ×1
optional ×1
parameters ×1
undefined ×1