gpt4 book ai didi

javascript - 空值和逻辑运算符不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:16 24 4
gpt4 key购买 nike

我想弄清楚为什么如果我输入空值,警报仍然会在不应该出现的时候出现。该参数声明所有值都不能为空,否则函数应该结束。

有人有什么想法吗?谢谢!

@charset "UTF-8";
/* CSS Document */

body{
height:1000px;
width:100%;
background:#fff;
margin:0;
}

.divider{
width:100%;
height:auto;
background:#CCC;
display:block;
margin:10px;
}

h2{
font-size:16px;
display:block;
}
#confirm-paragraph{}
#global-variable-paragraph{}
#user-input{}
#expressions{}
#elephant-paragraph{}
#method-1{}
#method-2{}
#ml{}
#litres{}
#conditional-operator{}
#cast-1{}
#cast-2{}
<!-- Checklist: Obtain user input and store it in variables -->
<!-- Report variable text to the client window -->
<!-- Prompt -->
<section class="divider">
<h2>User Input Variables Example</h2>
<button onclick="nameFunction()">Click Me</button>
<p id="user-input">This text should change after clicking the button.</p>
<p style="color:red; font-weight:bold">NOT WORKING Version3!!!!!!!!</p>
<p>Should not alert if null values are present - null values are present by just clicking OK when entering nothing. All values should not be null in order for the alert to appear</p>
<script>
function nameFunction() {
var yourforename = prompt("What is your first name?");
var yoursurname = prompt("What is your last name?");
var yourage = prompt("What is your age?");

if (yourforename != null && yoursurname != null && yourage != null) {
alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
}
}
</script>
</section>

最佳答案

我猜这是对返回值的混淆。如果您在提示中未键入任何内容,则会返回空字符串 ("")。但是,如果您单击取消按钮,则会返回 null。您的代码仅检查非 null"" 不等于 null,因此通过检查。快速修复可能是更改

if (yourforename != null && yoursurname != null && yourage != null) {
alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
}

if (yourforename && yoursurname && yourage) {
alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
}

关于javascript - 空值和逻辑运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739045/

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