最好的方法来检查对象中的键是否存在并设置值或null?

时间:2017-03-03 20:57:41

标签: javascript

我似乎正在使用支票let title = options.title ? options.title : null;并想知道是否有更好的最小化版本这样做?我记得看过一个ES6版本,但我不记得它是什么。

JS

this.options = options;
this.model = new Model({
        title: this.options.title ? this.options.title : null,
        message: this.options.message ? this.options.message : null,
        list: this.options.list ? this.options.list : null,
        errors: this.options.errors ? this.options.errors : null,
        innerHTML: this.options.html ? this.options.html : null
    });

2 个答案:

答案 0 :(得分:2)

options.hasOwnProperty('title'); 

返回布尔值(true或false)

或者您可以使用

title=options.title || null

答案 1 :(得分:2)

这样,您可以检查选项值和属性。你有这样的完全覆盖,所以js解释器不会抛出一个讨厌的错误。

title: ((this.options && this.options.title) || "defaultValue")
相关问题