typeof是一个运算符,有2种使用方式:typeof(表达式)和typeof 变量名,第一种是对表达式做运算,第二种是对变量做运算。
typeof 共返回6种数据格式:
1、object
2、undefined
3、string
4、number
5、boolean
6、function
javascript的typeof返回数据类型示例:console.log(typeof a); //'undefined'
console.log(typeof(true)); //'boolean'
console.log(typeof '123'); //'string'
console.log(typeof 123); //'number'
console.log(typeof NaN); //'number'
console.log(typeof null); //'object'
var obj = new String();
console.log(typeof(obj)); //'object'
var fn = function(){};
console.log(typeof(fn)); //'function'
console.log(typeof(class c{})); //'function'
特别注意Array和null返回的都是objectfunction show() {
console.log("var x; typeof(x) : "+typeof(x)); // undefined
console.log("typeof(10) : "+typeof(10)); // number
console.log("typeof('abc') : "+typeof('abc')); // string
console.log("typeof(true)"+typeof(true)); // boolean
console.log("typeof(function () { }) : "+typeof(function () { })); //function
console.log("typeof([1, 'a', true]) : "+typeof([1, 'a', true])); //object
console.log("typeof ({ a: 10, b: 20 }) : "+typeof ({ a: 10, b: 20 })); //object
console.log("typeof (new Number(10)) : "+typeof (new Number(10))); //object
console.log("typeof ($) : "+typeof ($)); //function
console.log("typeof (null) : "+typeof (null)); //Object
console.log("typeof (undefined) : "+typeof (undefined)); //undefined
}
更多web开发知识,请查阅 HTML中文网 !!