Javascript 如何使用默认值从对象中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9003999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:22:07  来源:igfitidea点击:

How to get value from Object, with default value

javascriptobject

提问by Jeremy S.

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?

jQuery/ExtJS 或任何其他框架是否提供了一种解决方案来以简单的方式访问这样的变量,并为变量提供默认值?

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 valuesalso sometimes contain parameter names.

然后将对象编码为参数字符串。但是正如您所看到的,对象有时也包含参数名称。

采纳答案by Jeremy S.

Looks like finally lodashhas the _.get()function for this!

看起来lodash终于有了_.get()函数!

回答by karim79

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

通常,当某个变量的计算结果为假时,可以使用or 运算符来分配默认值:

var foo = couldBeUndefined || "some default";

so:

所以:

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

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

假设config.args始终定义,正如您的示例代码所暗示的那样。

回答by Raynos

try var options = extend(defaults, userOptions);

尝试 var options = extend(defaults, userOptions);

This way you get all the userOptions and fall back to defaults when they don't pass any options.

通过这种方式,您可以获得所有 userOptions 并在它们不传递任何选项时回退到默认值。

Note use any extendimplementation you want.

请注意使用extend您想要的任何实现。