Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - How to get value from Object, with default value

I constantly find myself passing config values to functions accessing them like this:

var arg1 = 'test1';
if(isUndefined(config.args.arg1)){
  arg1 = config.args.arg1;
} 

var arg2 = 'param2';
if(isUndefined(config.args.arg2)){
  arg2 = config.args.arg2;
} 

var arg3 = '123';
if(isUndefined(config.args.arg3)){
  arg3 = config.args.arg3;
} 

where I later use them like this:

var url = '<some-url>?id='+arg1+'&='+arg2 +'=' + arg3;

Does jQuery/ExtJS or any other framework provide a solution to access variables like this in a simple way, and give variables a default value?

Something like:

getValueOfObject(config,'args.arg3','<default>');

Or is there maybe a standard solution for this.

NOTE:

I was also thinking about the common pattern where you have defaults

var defaults = {
   args: {
      args1: ....
   }
   ...
}

and doing an object merge.

And then encoding the object to a param String. But as you can see the object values also sometimes contain parameter names.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Generally, one can use the or operator to assign a default when some variable evaluates to falsy:

var foo = couldBeUndefined || "some default";

so:

var arg1 = config.args.arg1 || "test";
var arg2 = config.args.arg2 || "param2";

assuming that config.args is always defined, as your example code implies.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...