【问题标题】:Prevent value of 0 evaluating to false when using logical OR使用逻辑 OR 时防止将 0 的值评估为 false
【发布时间】:2019-04-27 00:16:43
【问题描述】:

我想知道是否有办法解决这个问题。我目前正在将一个值存储在一个变量中,如下所示:

Session['Score'] = 0; 

后来我有一个这样的任务:

Score = Session['Score'] || 'not set';

问题是,当Session['Score']如上设置为0时,JavaScript会将其解释为:

Score = false || 'not set';

这意味着Score 将评估为'not set' 而不是0

我该如何解决这个问题?

【问题讨论】:

  • 为什么不使用三元?顺便说一句,您可以使用负值。

标签: javascript boolean logical-operators short-circuiting


【解决方案1】:

现在您可以使用 nullish coalescing operator (??) 代替逻辑 OR。它类似于逻辑或,只是它只在左侧为空时返回右侧(nullundefined)而不是falsy

score = Session['Score'] ?? 'not set';

旧答案:

最干净的方法可能是设置值,然后检查它是否为假但不等于0

let score = Session['Score'];

if (!score && score !== 0) {
  score = 'not set';
}

正如Patrick Roberts 所述,您还可以选择将ternary operatorin 运算符结合使用:

Score = 'Score' in Session ? Session.Score : 'not set'

【讨论】:

  • 'Score' in Session ? Session.Score : 'not set'?
【解决方案2】:

您可以使用destructuring assignment

let { Score = 'not set' } = Session;

如果没有设置:

const Session = { };
let { Score = 'not set' } = Session;
console.log( Score ); 

如果设置为undefined以外的任何值,包括虚假值:

const Session = { Score: 0 };
let { Score = 'not set' } = Session;
console.log( Score ); 

【讨论】:

    【解决方案3】:

    改用字符串:

    Session['Score'] = "0";
    
    Score = Session['Score'] || 'not set';
    

    【讨论】:

    • @PatrickRoberts 真的吗?为什么?我认为一个字符串会解决它。
    • 真的吗?您将其发布为答案,而没有先尝试看看它是否有效?
    • 我没有代码,也不知道OP的上下文,所以无法测试。
    • var Session = {}; Session['Score'] = "0"; var Score = parseInt(Session['Score']) || 'not set'; console.log(Score); 似乎很简单,可以在那里创建一些上下文。
    【解决方案4】:

    您可以通过创建一些函数来更明确地表达您的意图:

    function getScore(s)
    {
        var result = s["Score"];
        if (result == null) {
            result = 0;
        }
        return result;
    }
    
    function addScore(s, v)
    {
        var result = s["Score"];
        if (result == null) {
            result = 0;
        }
        result += v;
        s["Score"] = result;
        return result;
    }
    
    var Session = {};
    document.write("Score ");
    document.write(getScore(Session));
    document.write("<p/>");
    addScore(Session, 10);
    document.write("Score ");
    document.write(getScore(Session));
    

    预期输出:

    Score 0
    
    Score 10
    

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2019-04-19
      • 1970-01-01
      • 2021-03-05
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      相关资源
      最近更新 更多