JavaScript测试数据类型的三种方法
程序员文章站
2022-06-07 14:32:41
# typeof console.log(typeof a); //undefined console.log(typeof(true)); //boolean console.log(typeof '111'); //string console.log(typeof 111); //number ......
# typeof
console.log(typeof a); //undefined
console.log(typeof(true)); //boolean
console.log(typeof '111'); //string
console.log(typeof 111); //number
console.log(typeof nan); //number
console.log(typeof null); //object
var str = new string();
console.log(typeof(str)); //object
var fn = function(){};
console.log(typeof(fn)); //function
class box{
constructor(){
}
}
var box = new box();
console.log(typeof box); //object
# object.prototype.tostring.call();
console.log(object.prototype.tostring.call("aaa")); //[object string]
console.log(object.prototype.tostring.call(111)); //[object number]
console.log(object.prototype.tostring.call(true)); //[object boolean]
console.log(object.prototype.tostring.call(undefined)); //[object undefined]
console.log(object.prototype.tostring.call(null)); //[object null]
console.log(object.prototype.tostring.call({name: "zhang"})); //[object object]
console.log(object.prototype.tostring.call(function(){})); //[object function]
console.log(object.prototype.tostring.call([])); //[object array]
console.log(object.prototype.tostring.call(new date)); //[object date]
console.log(object.prototype.tostring.call(/a/)); //[object regexp]
class test{
constructor(){
}
}
var test = new test();
console.log(object.prototype.tostring.call(test)); //[object object]
# constructor
console.log((111).constructor.name) //number
console.log(("111").constructor.name) //string
console.log((aaa).constructor.name) //aaa is not defined
console.log((/a/).constructor.name) //regexp
console.log((true).constructor.name) //boolean
console.log(({name:"zhang"}).constructor.name) //object
console.log((new date).constructor.name) //date
console.log(([]).constructor.name) //array
console.log((function(){}).constructor.name) //function
class box{
constructor(){
}
}
var test = new box();
console.log(test.constructor.name) //box
下一篇: 让你毛骨悚然的经典冷笑话