Default hash values

白昼怎懂夜的黑 提交于 2020-01-06 06:58:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14749020/default-hash-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!