如何使用默认值从Object获取值 [英] How to get value from Object, with default value

查看:127
本文介绍了如何使用默认值从Object获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己将配置值传递给访问它们的函数,如下所示:

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;

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

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?

类似于:

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

或者是否有标准的解决方案。

Or is there maybe a standard solution for this.

注意:

我也在考虑你有默认值的常见模式

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

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

并进行对象合并。

然后将对象编码为param String。但正如您所见,对象有时也包含参数名称。

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

推荐答案

看起来像是< _.get()的功能!

这篇关于如何使用默认值从Object获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆