gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:34 26 4
gpt4 key购买 nike

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

Session['Score'] = 0; 

后来我有这样的作业:

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

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

Score = false || 'not set';

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

我怎样才能解决这个问题?

最佳答案

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

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

旧答案:

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

let score = Session['Score'];

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

Patrick Roberts 所述, 您也可以选择使用 conditional (ternary) operator结合 in运算符(operator):

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

关于javascript - 使用逻辑或时防止 0 的值评估为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com