Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用逻辑OR时,防止0的值计算为false_Javascript_Boolean_Logical Operators_Short Circuiting - Fatal编程技术网

Javascript 使用逻辑OR时,防止0的值计算为false

Javascript 使用逻辑OR时,防止0的值计算为false,javascript,boolean,logical-operators,short-circuiting,Javascript,Boolean,Logical Operators,Short Circuiting,我想知道是否有办法解决这个问题。我当前在变量中存储一个值,如下所示: Session['Score'] = 0; 后来我有一个这样的作业: Score = Session['Score'] || 'not set'; 问题是,当会话['Score']如上设置为0时,JavaScript会将其解释为: Score = false || 'not set'; 这意味着得分将计算为“未设置”,而不是0 如何解决这个问题?请使用字符串: Session['Score'] = "0"; Scor

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

Session['Score'] = 0; 
后来我有一个这样的作业:

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

Score = false || '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));

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

let score = Session['Score'];

if (!score && score !== 0) {
  score = 'not set';
}
如所述,您还可以选择将与运算符结合使用:

Score = 'Score' in Session ? Session.Score : 'not set'
您可以通过以下方式执行此操作:

如果未设置:

const Session={};
设{Score='notset'}=Session;

控制台日志(Score)@PatrickRoberts真的吗?为什么?我以为用一根绳子就能修好,真的吗?你把它作为一个答案发布,而没有先尝试一下它是否有效?我没有代码,也不知道OP的上下文,所以我无法测试它。
var Session={};会话['Score']=“0”;var Score=parseInt(会话['Score'])| |“未设置”;控制台日志(Score)似乎很简单,可以在那里创建一些上下文。请稍候。在课时中查看我的测试
“分数”?Session.Score:“未设置”
?为什么不使用三元数?顺便说一句,您可以使用负值。
Score = 'Score' in Session ? Session.Score : 'not set'
let { Score = 'not set' } = Session;