Javascript 设置javascript对象属性的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6600868/
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
Set default value of javascript object attributes
提问by sandstrom
Is there a way to set the default attribute of a javascript object such that:
有没有办法设置 javascript 对象的默认属性,以便:
var emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue
IE can be disregarded, Chrome Frame has relieved me of that headache.
IE 可以无视,Chrome Frame 解决了我的头疼问题。
回答by sandstrom
Since I asked the question several years ago things have progressed nicely.
自从我几年前问这个问题以来,事情进展顺利。
Proxies are part of ES6. The following example works in Chrome, Firefox, Safari and Edge:
代理是 ES6 的一部分。以下示例适用于Chrome、Firefox、Safari 和 Edge:
var handler = {
get: function(target, name) {
return target.hasOwnProperty(name) ? target[name] : 42;
}
};
var p = new Proxy({}, handler);
p.answerToTheUltimateQuestionOfLife; //=> 42
Read more in Mozilla's documentation on Proxies.
在Mozilla 的 Proxy 文档中阅读更多内容。
回答by nrabinowitz
There isn't a way to set this in Javascript - returning undefined
for non-existent properties is a part of the core Javascript spec. See the discussion for this similar question. As I suggested there, one approach (though I can't really recommend it) would be to define a global getProperty
function:
没有办法在 Javascript 中设置它 - 返回undefined
不存在的属性是核心 Javascript 规范的一部分。请参阅此类似问题的讨论。正如我在那里建议的那样,一种方法(虽然我不能真正推荐它)是定义一个全局getProperty
函数:
function getProperty(o, prop) {
if (o[prop] !== undefined) return o[prop];
else return "my default";
}
var o = {
foo: 1
};
getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"
But this would lead to a bunch of non-standard code that would be difficult for others to read, and it might have unintended consequences in areas where you'd expect or want an undefined value. Better to just check as you go:
但这会导致一堆其他人难以阅读的非标准代码,并且可能会在您期望或想要未定义值的区域产生意想不到的后果。最好边走边检查:
var someVar = o.someVar || "my default";
回答by alexdriedger
Use destructuring(new in ES6)
使用解构(ES6 中的新功能)
There is great documentation by Mozilaas well as a fantastic blog postthat explains the syntax better than I can.
Mozila有很棒的文档,还有一篇很棒的博客文章,它比我能更好地解释语法。
To Answer Your Question
回答你的问题
var emptyObj = {};
const { nonExistingAttribute = defaultValue } = emptyObj;
console.log(nonExistingAttribute); // defaultValue
Going Further
走得更远
Can I renamethis variable? Sure!
我可以重命名这个变量吗?当然!
const { nonExistingAttribute: coolerName = 15} = emptyObj;
console.log(coolerName); // 15
What about nested data? Bring it on!
嵌套数据呢?来吧!
var nestedData = {
name: 'Awesome Programmer',
languages: [
{
name: 'javascript',
proficiency: 4,
}
],
country: 'Canada',
};
var {name: realName, languages: [{name: languageName}]} = nestedData ;
console.log(realName); // Awesome Programmer
console.log(languageName); // javascript
回答by jfriend00
This sure sounds like the typical use of protoype-based objects:
这确实听起来像是基于原型的对象的典型用法:
// define a new type of object
var foo = function() {};
// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";
// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1); // outputs defaultValue1
回答by Kiyan
my code is:
我的代码是:
function(s){
s = {
top: s.top || 100, // default value or s.top
left: s.left || 300, // default value or s.left
}
alert(s.top)
}
回答by Colin
The way I achieve this is with the object.assign
function
我实现这一点的方式是使用object.assign
功能
const defaultProperties = { 'foo': 'bar', 'bar': 'foo' };
const overwriteProperties = { 'foo': 'foo' };
const newObj = Object.assign({}, defaultProperties, overwriteProperties);
console.log(defaultProperties); // {"foo": "bar", "bar": "foo"}
console.log(overwriteProperties); // { "foo": "foo" };
console.log(newObj); // { "foo": "foo", "bar": "foo" }
回答by user1386350
Or you can try this
或者你可以试试这个
dict = {
'somekey': 'somevalue'
};
val = dict['anotherkey'] || 'anotherval';
回答by gianlucaparadise
I think the simplest approach is using Object.assign
.
我认为最简单的方法是使用Object.assign
.
If you have this Class:
如果你有这个类:
class MyHelper {
constructor(options) {
this.options = Object.assign({
name: "John",
surname: "Doe",
birthDate: "1980-08-08"
}, options);
}
}
You can use it like this:
你可以这样使用它:
let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"
Documentation (with polyfill): https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
文档(带有 polyfill):https: //developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
回答by Gil Baggio
Simplest of all Solutions:
最简单的解决方案:
dict = {'first': 1,
'second': 2,
'third': 3}
Now,
现在,
dict['last'] || 'Excluded'
will return 'Excluded', which is the default value.
将返回“排除”,这是默认值。
回答by joaquin keller
This seems to me the most simple and readable way of doing so:
在我看来,这是最简单易读的方法:
let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}
options = Object.assign({}, default_options, options)