简体   繁体   English

如果javascript中的else陈述无法正常运作

[英]if else statement in javascript not working properly

As you can see from this code: 从此代码中可以看到:

function setBodyClasses() {
    var answer = $surveyAns.getAnswer('QUEST223');
    answer = 'oro';
    if(!surveyUtils.isNullOrWhiteSpace(answer)) {
        if (answer.toLowerCase().indexOf('oro')) {
            $scope.bodyClasses = 'vip_gold';
        }
        else if (answer.toLowerCase().indexOf('platino')) {
            $scope.bodyClasses = 'vip_platinum';
        }
        else {
            $scope.bodyClasses = '';
        }
    }
}

For some reason the if else statement is not working correctly, as you can see the answer value is oro and it should stop on the first if, but when its on the first if condition it compares the value and it moves forward assuming that is not the same value, and for some other reason it enters the second if condition even though the value is different. 出于某种原因,if else语句无法正常工作,因为您可以看到答案值是oro,它应该在第一个if处停止,但是在第一个if条件下,它会比较该值,并假设不是相同的值,并且由于其他一些原因,即使值不同,它也会输入第二个if条件。 Any idea why this is happening? 知道为什么会这样吗?

You are incorrectly checking if answer contains the string. 您错误地检查了answer包含字符串。 .indexOf() will return you where in the string it is. .indexOf()将返回您在字符串中的位置。 It could be 0 , that's the start of the string (it's like an array, where it's zero-indexed). 它可以是0 ,这是字符串的开头(就像一个数组,在这里它的索引为零)。 It returns -1 if it's not found. 如果找不到,它将返回-1

If you just do if(answer.toLowerCase().indexOf('oro')) it will be false , since 0 is "falsly". 如果只执行if(answer.toLowerCase().indexOf('oro'))则它将为false ,因为0为“ falsly”。

You want to do: if(answer.toLowerCase().indexOf('oro') >= 0) . 您要执行以下操作: if(answer.toLowerCase().indexOf('oro') >= 0)

Are you sure you want to use indexOf() in the first place? 您确定要首先使用indexOf()吗? This is checking if the string "contains" oro . 这是在检查字符串“ contains”是否为oro Are you sure you don't just need: if(answer.toLowerCase() === 'oro') ? 您确定不只是需要: if(answer.toLowerCase() === 'oro')吗?

indexOf is returning 0, and 0 is a falsy value so its not entering the condition. indexOf返回0,并且0是一个伪造的值,因此它没有进入条件。 Should be: 应该:

.indexOf('oro') > -1

Same with the other conditions 与其他条件相同

You are using indexOf to find the existence of "oro" in your string. 您正在使用indexOf查找字符串中是否存在“ oro”。 IndexOf, however, correctly returns a value of 0, which equates to false in JavaScript. 但是,IndexOf正确返回值0,在JavaScript中等于false。 I personally would use answer.indexOf('oro') !== -1 . 我个人将使用answer.indexOf('oro') !== -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM