默认哈希值 [英] Default hash values

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

问题描述

我想用 defaults 默认值 params 成员的散列:

  var defaults = {item1:def1,item2:def2}; 
var params = {item2:param2,item3:param3};
var result = //这里有一些聪明的代码...
console.log(result); // {item1:def1,item2:param2,item3:param3};

我能想出的最聪明的代码是迭代 defaults 成员,并将它们添加到 params 中(如果它们在那里丢失)。我想知道是否有一些本地解决方案,而不是编写自己的代码?原型设计看起来很有前途,但它只适用于功能对象,我不想在这里。任何想法?如果有人仍然感兴趣:在将近两年后,我想这个问题中提到的巧妙的代码将会是

  __ proto__:Object.create(默认值)

查看示例:

  var defaults = {item1:def1,item2 :def2}; 
var params = {item2:param2,item3:param3,
__proto__:Object.create(defaults)};

for(var i in params)console.log(i,params [i]);
// item2 param2
// item3 param3
// item1 def1

请记住 __ proto __ 不推荐使用,但是与链接建议的 setPrototypeOf()方法不同。让我们看看未来会是什么。


I'd like to have a hash with params members with defaults default values:

var defaults = { item1: "def1", item2: "def2" };
var params = { item2: "param2", item3: "param3" };
var result = // some clever code here...
console.log(result); // { item1: "def1", item2: "param2", item3: "param3" };

The most clever code I can figure out is to iterate defaults members and add them into params if they are missing there. I wonder if there is some native solution instead of writing own code? Prototyping seems promising, but it only works with functional objects, which I don't want here. Any thoughts?

解决方案

If anyone is still interested: after almost two years, I guess the clever code mentioned in the question would be

__proto__: Object.create(defaults)

See the example:

var defaults = { item1: "def1", item2: "def2" };
var params = { item2: "param2", item3: "param3",
  __proto__: Object.create(defaults) };

for(var i in params) console.log(i,params[i]);
// item2 param2
// item3 param3
// item1 def1

Just keep in mind that the __proto__ is deprecated, however well supported unlike the setPrototypeOf() method suggested by the link. Let's see what the future will be.

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

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