空值和逻辑运算符不工作

时间:2017-03-11 18:33:16

标签: javascript html css

我试图找出为什么如果我输入空值,警告仍然会出现,但不应该出现。该参数声明所有值都不能为null,否则函数应该结束。

有没有人有任何想法?谢谢!



@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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

如果你警告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.");
}

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

相关问题