我试图弄清楚为什么如果我输入空值,警告仍然出现在不应该出现的时候。参数声明所有的值都不能为空,否则函数应该结束。
有谁有什么想法吗?谢谢!
@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>
发布于 2017-03-12 02:39:06
我猜这是对返回值的混淆。如果在提示符中不键入任何内容,则返回空字符串("")。但是,如果单击cancel按钮,则返回null。您的代码只检查非null。""不等于null,因此pass会进行检查。一种快速的解决办法可能是改变
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.");
}发布于 2017-03-12 02:38:59
如果您警告typeof yourforename变量等...您将看到它返回一个字符串。因此,如果将if语句重写如下:
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 > '' && yoursurname > '' && yourage > '') {
alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
}看起来不错。因为您现在正在检查字符串的长度是否大于空的''。
https://stackoverflow.com/questions/42739045
复制相似问题