Javascript对象属性 - 如果不存在则创建属性

时间:2015-12-22 15:22:10

标签: javascript if-statement null try-catch

我试图以最优雅的方式执行这段代码:

if (internalTableName in self.columnMap &&
    internalColumnName in self.columnMap[internalTableName]) {
    console.error('dupelicates');
}
else {
    try {
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    } catch (err) {
        self.columnMap[internalTableName] = {};
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    }
}

我可以将try / catch块转换为:

if (internalTableName in self.columnMap &&
    internalColumnName in self.columnMap[internalTableName]) {
    console.error('dupelicates');
}
else {
    if (internalTableName in self.columnMap) {
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    }
    else {
        self.columnMap[internalTableName] = {};
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;

    }
}

我想知道Javascript是否提供了一些检查无效的运算符,这些运算符可以使这个逻辑以更优雅的方式编写,并减少IF子句。

谢谢

2 个答案:

答案 0 :(得分:2)

常见模式使用|| operator

self.columnMap[internalTableName] = self.columnMap[internalTableName] || {};
self.columnMap[internalTableName][internalColumnName] = logicalColumnName;

答案 1 :(得分:1)

我认为你在寻找的是

if (!(internalTableName in self.columnMap))
    self.columnMap[internalTableName] = {};
if (!(internalColumnName in self.columnMap[internalTableName]))
    self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
else
    console.error('duplicates');

您可以使用辅助变量缩短它,并通过简单的虚假检查空属性:

var table = self.columnMap[internalTableName] || (self.columnMap[internalTableName] = {});
if (!table[internalColumnName])
    table[internalColumnName] = logicalColumnName;
else
    console.error('duplicates');