如何减少JavaScript中的if语句
if(obj.attributes && obj.attributes.email === 'test@test.com') { ... }
答案 0 :(得分:1)
这行代码很清楚,但是,如果您正在寻找一种在内部编写较少&&
运算符的方法,则可以始终将诸如此类的内容放在比较之外。
var attributes = obj.attributes || {};
if ( attributes.email === 'test@test.com' ) {
}
这很有意义,如果您需要进行多次检查而不是一次检查,但是如果是一次比较,则似乎已经存在的代码就可以了,因为您可以确保在访问attributes
之前已定义了{ undefined
属性。
另一方面,如果您支持ES 2015,则可以销毁以下内容:
const { attributes = {} } = obj;
if ( attributes.email === 'test@test.com' ) {
}
答案 1 :(得分:0)
您可以使用get
创建可重用的Array.reduce()
函数。函数参数是路径,对象和defaultValue(默认defaultValue
为undefined
)。它将迭代路径,并尝试提取值,如果失败,它将返回defaultValue
:
const get = (path, obj, defaultValue) => obj ?
path.reduce((r, k) => r && typeof r === 'object' ? r[k] : defaultValue, obj)
:
defaultValue;
if(get(['attributes', 'email'], null) === 'test@test.com') { console.log(1) }
if(get(['attributes', 'email'], {}) === 'test@test.com') { console.log(2) }
if(get(['attributes', 'email'], { attributes: {} }) === 'test@test.com') { console.log(3) }
if(get(['attributes', 'email'], { attributes: { email: 'test@test.com' } }) === 'test@test.com') { console.log(4) }
有一个称为"Optional Chaining for JavaScript"的TC39阶段提案。如果可以使用该语言,它将添加一个可选的链接运算符-?
。现在,如果attributes
不存在,它将返回undefined
。
示例:obj.attributes?.email
今天可以通过babel plugin使用。