小学生

- 金币
- 110
- 好评
- 0
- 信誉
- 100

|
JavaScript一共有7中数据类型:
null, undefined, string, number, boolean, object, symbol(ES6)
前面5种为基本类型
object又包括 array,function,date等
1.使用typeof判断数据类型
typeof 5;//number
typeof '5';//string
typeof undefined;//undefined
typeof true;//boolean
typeof null;//object
typeof Symbol('er');//Symbol
typeof {};//object
2.使用instanceof判断数据类型
a instanceof B 判断的是 a是否是B的实例
2.1数组的判断
[1,2,3] instanceof Array;//true
2.2 对象的判断
function Person(name){
this.name = name;
}
const p = new Person('lucy');
p instanceof Person;//true
2.3 数字的判断
5 instanceof Number;//false
5是基本类型,它并不是Number构造函数构造出来的实例对象,稍加修改,使其变为判断以下关系,则返回true。
new Number(5) instanceof Number;//true
3.使用Object.prototype.toString判断数据类型
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call('lucy'));//[object String]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call({}));//[object Object]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(()=>{}));//[object Function]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call(Symbol('345')));//[object Symbol]
4.使用constructor查看目标的构造函数,也可以进行数据类型判断
var foo = 5;
foo.constructor
//ƒ Number() { [native code] }
var foo = 'lucy';
foo.constructor
//ƒ String() { [native code] }
var foo = true;
foo.constructor
//ƒ Boolean() { [native code] }
var foo = [];
foo.constructor
//ƒ Array() { [native code] }
var foo = {};
foo.constructor
//ƒ Object() { [native code] }
var foo = ()=>{
};
foo.constructor
//ƒ Function() { [native code] }
var foo =Symbol('345')
foo.constructor
//ƒ Symbol() { [native code] } |
|