【问题标题】:How to turn ternary if statement back into standard javascript?如何将三元 if 语句转换回标准 javascript?
【发布时间】:2013-10-24 00:59:19
【问题描述】:

我正在使用这个三元 if 语句:

a[textProp] = _newText + ' (' + (_newText === a[textProp] ? 'no change' : 'changed') + ')';

我想把它改回标准的javascript(为了可读性)。我还想把它变成一个 if、else if、else 语句来测试变量是否为空/null。

这是我拥有的,但不起作用:

if (_newText = null) {
'Invalid Record';
}
else if (_newText === a[textProp]) {
'no change';
}
else(_newText != a[textProp]) {
'changed';
}
+ ')';

【问题讨论】:

  • else 语句中使用测试不会出错?

标签: javascript ternary-operator


【解决方案1】:
if (_newText = null) {
             ^

需要

if (_newText == null) {
             ^^

if (_newText === null) {
             ^^^

你需要建立你的字符串

a[textProp] = 'Invalid Record';

【讨论】:

    【解决方案2】:

    为了可读性,我会从这样的内容开始,其中每个状态都被显式检查(有效和更改):

    var isValid = true;
    if (_newText == null || _newText.trim().length === 0) {
      isValid = false;
    }
    
    var hasChanged = false;
    if (isValid && _newText !== a[textProp]) {
      hasChanged = true;
    }
    
    if (!isValid) {
      a[textProp] = 'Invalid Record';
    }
    else if (hasChanged) {
      a[textProp] = _newText + ' (changed)';
    }
    else {
      a[textProp] += ' (no change)';
    }
    

    但是,我也认为将测试结果作为字符串存储在a[textProp] 中是不正确的,它可能会使以后的测试无效。我可能有单独的测试结果键(作为标志),例如:a.valid[textProp]a.changed[textProp](在这种情况下,textProp 永远不能是 "valid""changed")。更好的办法是将文本存储在 a[textProp].text 中,并将标志存储在 a[textProp].valida[textProp].changed 中。

    【讨论】:

    • 我仍然无法让无效记录正常工作。看看我的小提琴jsfiddle.net/pfeff/WnaBD/1
    • 试试this one。请注意,如果您多次单击该按钮,就会发生我提到的情况。
    • 我之前确实注意到了这一点,但请查看第 9 个列表项。它没有记录号,所以我希望将“无效”之类的东西附加到它上面,而不是没有变化。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    相关资源
    最近更新 更多