使用逻辑或时防止 0 的值评估为 false

Prevent value of 0 evaluating to false when using logical OR

我想知道是否有办法解决这个问题。我目前正在这样的变量中存储一个值:

Session['Score'] = 0; 

稍后我有这样的作业:

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

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

Score = false || 'not set';

这意味着 Score 将计算为 'not set' 而不是 0!

我该如何解决这个问题?

改用字符串:

Session['Score'] = "0";

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

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

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

现在您可以使用 nullish coalescing operator (??) instead of the logical OR. It is similar to the logical OR, except that it only returns the right-hand side when the left-hand side is nullish (null or undefined) instead of falsy

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

旧答案:

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

let score = Session['Score'];

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

, you could also choose to use the ternary operator in combination with the in 操作员所述:

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

您可以使用 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 );