Tuesday, 10 October 2017

Javascript - function with optional parameters as object?

itemprop="text">

I need a function that its parameter
is an object, and if I leave it empty it will load default
values.



something
like:



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 one
default and one custom value
loadMap({latitude:
"x.xxxx"});


I found
this solution in this question ( href="https://stackoverflow.com/questions/148901/is-there-a-better-way-to-do-optional-function-parameters-in-javascript">Is
there a better way to do optional function parameters in Javascript?) but it
requires jQuery:
http://jsfiddle.net/xy84kwdv/



It's
ALMOST what I want but I don't want to depend on a jquery function.



Answer




Are you looking for something like:




function loadMap(args)
{
args = args || {};
args.latitude = args.latitude || "X.XXX";

args.longitude = args.longitude || "Y.YYY";

alert(args.latitude);
alert(args.longitude);
};


loadMap({latitude:"custom_latitude"});



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...