【问题标题】:Null values & logical operators not working空值和逻辑运算符不起作用
【发布时间】:2017-08-02 00:25:37
【问题描述】:

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

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

@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>

【问题讨论】:

  • 很确定如果你没有在prompt 中输入任何内容,它会返回一个空字符串而不是null。此外,您可以删除 CSS/HTML 代码并删除两种语言的标签,因为它们与您的问题无关。

标签: javascript html css


【解决方案1】:

我猜这是对返回值的混淆。如果您在提示中不输入任何内容,则返回空字符串 ("")。但是,如果单击取消按钮,则返回 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.");
    }

【讨论】:

  • 您不希望在更正版本中使用前缀 ! 运算符。
  • 好收获!我修好了。
【解决方案2】:

如果您提醒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.");
}

它会起作用的。因为您现在正在检查字符串的长度是否大于空的''

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多