3 回答
TA贡献1777条经验 获得超3个赞
我想知道这两种方法中是否有任何性能差异...
是的,勉强;通常使用异常机制比简单的分支成本更高,尽管当你抛出的东西不是时,它在JavaScript中(与其他一些语言相比)没有太大的区别(因为当你不创建时,不需要捕获堆栈信息)。Error
Error
...以及应使用哪种方法来执行此类操作。
通常,异常处理适用于特殊情况,而不是预期的情况。对于您描述的内容,标准方法将是第一个,即简单分支。您可以将字符串存储在一个简单的变量中,然后在 // 之后赋值:innerHTML
if
else if
else
function validateAge() {
var agge = document.getElementById("age").value;
var message;
if (agge == "") {
message = "Please enter your age";
} else if (agge < 18) {
message = "You are too young to vote";
} else {
message = "You are eligible to vote";
}
document.getElementById("result").innerHTML = message;
}
function validateAge() {
var agge = document.getElementById("age").value;
var message;
if (agge == "") {
message = "Please enter your age";
} else if (agge < 18) {
message = "You are too young to vote";
} else {
message = "You are eligible to vote";
}
document.getElementById("result").innerHTML = message;
}
<title>Age validator</title>
<h1>Enter your age to check if you are eligible to vote : </h1>
<label>Enter Your age : </label>
<input type="text" id="age" /><br/>
<input type="button" onclick="validateAge()" value="Validate" /><br/>
<p id="result"></p>
..但这主要是风格问题。
不过,可能更重要的是,最好检查用户输入的内容是否实际上是一个数字。使用您当前的代码,如果我在字段中编写,我被告知我有资格投票,因为评估值会评估为 。seven
"seven" < 18
NaN < 18
false
TA贡献1815条经验 获得超10个赞
这将更快。
function validateAge() {
var age = document.getElementById("age").value
document.getElementById("result").innerHTML = age?age<18?"You are too young to vote":"You are eligible to vote":"Please enter your age"
}
<title>Age validator</title>
<h1>Enter your age to check if you are eligible to vote : </h1>
<label>Enter Your age : </label>
<input type="number" id="age" /><br/>
<input type="button" onclick="validateAge()" value="Validate" /><br/>
<p id="result"></p>
TA贡献1851条经验 获得超4个赞
您的第二个代码必须处理抛出/捕获
以下内容可能会更快,但不会明显如此
var text;
if (age.trim() === "") text = "Please enter your age";
else if (isNaN(age)) text = "That is not an age";
else text = +age < 18 ? "You are too young to vote" : "You are eligible to vote";
paragraph.textContent = text;
window.addEventListener("load", function() {
document.getElementById("validate").addEventListener("click", function(e) {
e.preventDefault();
var age = document.getElementById("age").value;
var paragraph = document.getElementById("result");
var text;
if (age.trim() === "") text = "Please enter your age";
else if (isNaN(age)) text = "That is not an age";
else text = +age < 18 ? "You are too young to vote" : "You are eligible to vote";
paragraph.textContent = text;
});
});
<title>Age validator</title>
<h1>Enter your age to check if you are eligible to vote : </h1>
<label>Enter Your age : </label>
<input type="text" id="age" /><br/>
<input type="button" id="validate" value="Validate" /><br/>
<p id="result"></p>
添加回答
举报