检查JS可选属性是否存在最有效(或最具风格)的方法?

时间:2015-08-08 00:51:13

标签: javascript coding-style

考虑一个对象user

user = {
    profile: {
        first_name: "Arthur",
        last_name:  "Dent"
    },
    planet: "Earth"
}

检查user.profile.first_name是否存在的最佳方式是什么?

我通常使用(!!user && !!user.profile && !!user.profile.first_name),但这可能是最好的方法(特别是在较长的情况下,属性更深的嵌套)。

很好奇这是如何做到的!

[编辑] 为了论证,考虑一下你需要检查users.jordan.profile.favorites.color(故意长而笨拙)的存在,你无法确定是否存在任何单个属性(因此users.jordan可能存在但users.jordan.profile不存在。)

当然,这可能是代码中普遍出现问题的一个迹象(例如,除非填充所有可能的属性,否则不应该创建对象),但有时候这无法帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用in检查if语句中的属性。

if ('profile' in user) {
    alert('I have a profile!');
}

如果您需要检查嵌套值,请查看该属性:

if ('first_name' in user.profile) {
    alert('I have a first name!');
}

您也可以使用.hasOwnProperty()

if (user.hasOwnProperty('profile') {
    alert('I have a profile!');
}

答案 1 :(得分:1)

我会使用try catch块:

try { fname = user.profile.first_name } catch(e) { fname = false }
if (fname) ...