简体   繁体   English

无法理解这个逻辑运算符的行为

[英]Can't wrap my head around the behavior of this logical operator

I was messing around with some simple exercises and found something that I thought acted quite odd. 我在搞一些简单的练习,发现我认为有些奇怪的事情。 I wrote a very simple HTML form that when a user enters their name, if it was Bob or Alice it would great them. 我写了一个非常简单的HTML表单,当用户输入他们的名字时,如果它是BobAlice话,它们会很不错。 If it was another name, it would say I don't know you. 如果这是另一个名字,它会说I don't know you. So, my thought was to use a logical operator to compare the username that was entered. 因此,我的想法是使用逻辑运算符比较输入的用户名。 Here is my code: 这是我的代码:

<h1>This is the practice space</h1>
    <div id="output">
        <label>what is your name?</label>
        <input id="name" type="text">
        <button type="button" onclick="getName()">Send it through!</button>
        <span id="output-name"></span>
    </div>

    <script>
        function getName(){

            var userName = document.getElementById('name').value;

            if(userName === 'Alice' || 'Bob'){
                document.getElementById('output-name').innerHTML = 'Hello ' + userName + '! Glad to have you!';
            } else {
                document.getElementById('output-name').innerHTML = 'I don\'t know you.';
            }
        }
    </script>

To me this says "if userName is equal to Alice , then true, If not, if userName equals to Bob then true. If not, then I don't know you. That is not the case. Everything that I enter is passing as true and nothing is passing as false. Can anyone make any sense of this? 对我来说,这是“如果userName等于Alice ,则为true,否则为true,如果userName等于Bob ,则为true。否则, I don't know you.情况并非如此。我输入的所有内容都以正确,没有任何事物能像错误一样传递。任何人都可以理解吗?

By the way, I read through the documentation on MDN specifically to find out the logic in these logical operators. 顺便说一句,我通读了有关MDN的文档,专门研究了这些逻辑运算符中的逻辑。 I thought by what I read, my code should work. 我以为我读到的代码应该可以工作。

That is because you're not checking anything against 'Bob' . 那是因为您没有对'Bob'检查。

Change: 更改:

if(userName === 'Alice' || 'Bob')

To: 至:

if(userName === 'Alice' || userName === 'Bob')

The reason your current code returns true all the time is because strings, unless empty, are truthy . 当前代码始终返回true的原因是因为字符串(除非为空)是true 'Bob' evaluates to true , so your if statement is quite literally saying: If the username is equal to Alice, or if this is true, then... . 'Bob'计算结果为true ,因此您的if语句从字面上说: 如果用户名等于Alice,或者如果它为true,则...。 if ('Bob') will always be true. if ('Bob')始终为true。

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

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