NaN的神奇
前言:
在弄音谱可视化的时候遇到一些尴尬的问题,不断调试之后才发现是NaN的问题,于是在下通过参考他人的经验与自己敲代码来了解一下NaN;
NaN的官方解说:
NaN 属性是代表非数字值的特殊值。该属性用于指示某个值不是数字。可以把 Number 对象设置为该值,来指示其不是数字值。
提示:请使用 isNaN() 全局函数来判断一个值是否是 NaN 值。
以上来自w3school
当然还有大神的解说:
参考->JS中NaN定义与用法
本人自己尝试了一下:
代码:
<!DOCTYPE html>
<html>
<head>
<title>NaN报告</title>
<meta charset="utf-8">
</head>
<body>
<input type="text" name="" value=1 id="demo_input">
<script type="text/javascript">
var a = "aba";
var b = document.getElementById('demo_input');
var c = b.value;
var d = "1";
var e = "01";
var f =" 1";
var g = "m12";
var h = "12m";
var i = "12 m";
console.log("\"aba\" 是NaN:"+isNaN(a));
console.log("document.getElementById('demo_input') 是NaN:"+isNaN(b));
console.log("b.value 是NaN:"+isNaN(c));
console.log("\"1\" 是NaN:"+isNaN(d));
console.log("\"01\" 是NaN:"+isNaN(e));
console.log("\" 1\" 是NaN:"+isNaN(f));
console.log("\"m12\" 是NaN:"+isNaN(g));
console.log("\"12m\" 是NaN:"+isNaN(h));
console.log("\"12 m\" 是NaN:"+isNaN(i));
console.log("-----------------------------");
console.log("parseInt(a):" + parseInt(a));
console.log("parseInt(b):" + parseInt(b));
console.log("parseInt(c):" + parseInt(c));
console.log("parseInt(d):" + parseInt(d));
console.log("parseInt(e):" + parseInt(e));
console.log("parseInt(f):" + parseInt(f));
console.log("parseInt(g):" + parseInt(g));
console.log("parseInt(h):" + parseInt(h));
console.log("parseInt(i):" + parseInt(i));
console.log("-----------------------------");
console.log("Number(a):" + Number(a));
console.log("Number(b):" + Number(b));
console.log("Number(c):" + Number(c));
console.log("Number(d):" + Number(d));
console.log("Number(e):" + Number(e));
console.log("Number(f):" + Number(f));
console.log("Number(g):" + Number(g));
console.log("Number(h):" + Number(h));
console.log("Number(i):" + Number(i));
console.log("-----------------------------");
var number = 1;
console.log("var number = 1;");
console.log("number + b.value = "+ (number + b.value));
console.log("number + 1 * b.value ="+ (number + 1 * b.value));
console.log("number + parseInt( b.value ) = " + (number + parseInt( b.value )));
console.log("number + Number( b.value) = " + (number + Number( b.value)));
</script>
</body>
</html>
以上可以忽略
以下是控制台的结果
结果
“aba” 是NaN:true
document.getElementById(‘demo_input’) 是NaN:true
b.value 是NaN:false
“1” 是NaN:false
“01” 是NaN:false
” 1” 是NaN:false
“m12” 是NaN:true
“12m” 是NaN:true
“12 m” 是NaN:true
parseInt(a):NaN
parseInt(b):NaN
parseInt(c):1
parseInt(d):1
parseInt(e):1
parseInt(f):1
parseInt(g):NaN
parseInt(h):12
parseInt(i):12
Number(a):NaN
Number(b):NaN
Number(c):1
Number(d):1
Number(e):1
Number(f):1
Number(g):NaN
Number(h):NaN
Number(i):NaN
var number = 1;
number + b.value = 11
number + 1 * b.value =2
number + parseInt( b.value ) = 2
number + Number( b.value) = 2
上一篇: JS中的NaN
下一篇: 如何理解RESTful API