NaN
NaN是number类型中一个特殊的数值,在JavaScript中它有个奇怪的定义:非数值(Not a Number),即是一个不是数字的数值,这个数值用于表示一个本来要返回数值的操作数未返回数值的情况。
在其他语言中,任何数值在未返回都会得到错误,但在JS中,会返回NaN,这样它就不会抛出错误了,继续解析执行接下来的代码。
console.log(typeof NaN); //返回Number
NaN的特点
1.任何数值除以非数值(字符串、undefined、object)都会返回NaN。
var div = document.getElementById("div");
console.log("aaaaa"/3); //返回NaN
console.log(undefined/ 5 ); //返回NaN
console.log(div / 1); //返回NaN
注意:
1.1**Boolean**和Null(关于Null的解释在介绍isNaN函数会提到)因为在过程中会自动转换成number类型,所以会得到正确的数字。
2.NaN与任何值都不相等,包括NaN自身。
console.log(NaN == NaN); //返回false
console.log(NaN === NaN); //返回false
console.log(NaN == -1); //返回false
isNaN()方法
该函数接收一个参数,这个参数可以是任何类型,如果接收的参数是数字类型,返回false;如果是其他类型(除了数字的任何其他类型),则返回true;
注意:
1.该方法在接收参数后,如果传入的参数类型不是数字类型,会尝试将该参数转换为数字类型,以下有代码例子。
2.如接受的参数是空,比如[](空数组)、“”(空字符串)等,会在过程中转换为数字类型的0,从而返回false;
3.如果传入的参数为Null,也会返回false,但我个人用类型转换方法转换Null的时候,会将null转换为NaN,根据国外StackOverFlow论坛中的答主解释,在isNaN函数里,null是空值,就是0,所以会返回false。参考网址:http://stackoverflow.com/questions/115548/why-is-isnannull-false-in-js
console.log(isNaN(100)); //返回false
console.log(isNaN("100")); //字符串“100”被转换为数字100,所以返回false
console.log(isNaN("aaa")); //返回true
console.log(isNaN(true)); //true转换为数字1,所以返回false
console.log(isNaN("")); //空值会被转换为0,所以返回false
console.log(isNaN(NaN)); //返回true
console.log(isNaN([])); //空值会被转换为0,所以返回false
console.log(isNaN(null)); //null会被转换成0,所以返回false
isNaN()方法的运用的小例子
以下是我做的一个运用NaN检测的简单小例子:
用来检测成绩输入是否正确(0-100),如不是,则出现警告
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin:0;
padding: 0;
font-size: 17px;
}
div{
margin:100px auto;
height: 30px;
width: 450px;
}
input{
width: 150px;
height: 30px;
line-height: 30px;
box-sizing: border-box;
}
span{
width: 150px;
line-height: 30px;
display: inline-block;
text-align: center;
font-size: 13px;
color:#fff;
}
.info{
border:1px solid #40899E;
background: #5BC0DE;
}
.danger{
border:1px solid #D33A34;
background: #D9544F;
}
.success{
border:1px solid #48AC49;
background: #57B658;
}
</style>
</head>
<body>
<div>
<label>请输入成绩:</label>
<input type="text" name="grade" id="grade">
<span class="info">请输入</span>
</div>
<script type="text/javascript">
window.onload = function(){
var grade = document.getElementById("grade");
var span = document.getElementsByTagName("span")[0];
grade.onblur = function(){
//获得输入内容
var value = grade.value;
//判断是否大于100或者小于0
if(value < 0 || value > 100){
span.className = "danger";
span.textContent = "请输入0-100内的数字";
}
//判断是否为数字类型
else if(isNaN(value)){
span.className = "danger";
span.textContent = "请输入数字";
}
else{
span.className = "success";
span.textContent = "输入正确";
}
}
}
</script>
</body>
</html>