JS中数据类型如何判断
JS中判断数据类型主要有两种方式:typeof,instanceof 运算符
typeof
语法:typeof 变量名 / 字面量
返回值:“number”、“string”、“boolean”、“object”、“function” 和 “undefined”
如果运算数未定义,则返回undefined
数据类型 | 返回值 | 其他说明 |
---|---|---|
typeof “true” | string | |
typeof 12 | number | |
typeof new Number(“12”) | object | |
typeof true | boolean | |
typeof null | object | |
typeof undefined | undefined | |
typeof {} | object | |
typeof [1,2] | object | |
typeof function(){} | function | |
typeof(window) | object | |
typeof(Object) | function | Object 是 JS的内置函数 |
typeof的应用:
用于判断一个变量是否有值,限制后续操作。
//判断变量a是否有值
if(typeof a!="undefined"){}
//if(a) 这种写法是错误的,a 不存在(未声明)则会出错
console.log(typeof a); // undefined
console.log(a); // 报错
// 判断一个变量是否是数组
var myList = document.getElementsByTagName("li");
if( typeof(myList.length ) != "undefined" ) {
……
// 说明数组有值
}
//或
if( !isNaN(mylist.length)) {}
typeof的局限性:
对于 arrayObject,null 等特殊值使用 typeof 一律返回 object
instanceof
语法:obj instanceof constructor
返回值:true,false
参数:obj(要检测的对象实例)constructor(某个构造函数)
描述:obj 的 proto 一层一层往上,能否对应到 constructor.prototype
原理:通过检测一个对象在其原型链中是否存在一个构造函数的 prototype 属性,检测某个对象是不是另一个对象的实例。
- obj 若是基本类型,返回false
"1" instanceof String // false
"1" instanceof Object// false
- obj 为 null 或者 undefined
null instanceof Object//false
undefined instanceof Object //false
- obj 为引用数据类型
{} instanceof Object //true
window instanceof Object // true
function(){} instanceof Object //true
function(){} instanceof Function //true
[] instanceof Array // true
[] instanceof Object // true
- obj 为JS对象的实例( 即是通过new 操作符创建)
new String() instanceof String //true
new String() instanceof Object // true
new Date() instanceof Date // true
new Array() instanceof Array // true
isNaN(number)
在JS中,因为NaN != NaN,用isNaN(number)来判断参数是不是NaN
是返回 true,不是返回 false