JavaScript 6 数据类型

197 阅读1分钟

基础类型

Number,String,Boolean,Undefined,Null,Symbol

引用类型

Object,Function,Array,Regexp

类型判断

typeof

console.log(typeof (123))  // number
console.log(typeof ("123")) // string
console.log(typeof (false)) // boolean
console.log(typeof (undefined)) // undefined
console.log(typeof (null)) // object

console.log(typeof ({})) // object
console.log(typeof (function(){})) // function
console.log(typeof ([])) // object
console.log(typeof (new String())) // object

typeof 可以判断除null外的基础数据类型

基础数据类型检测方法
function dataType(data){
    return data==null?null:typeof(data)
}

instanceof

console.log(123 instanceof Number) // false
console.log("123" instanceof String) // false
console.log(true instanceof Boolean) // false
// console.log(undefined instanceof Undefined) // 报错
// console.log(null instanceof Null) // 报错
console.log([] instanceof Array) // true
console.log({} instanceof Object) // true
console.log(function(){} instanceof Function) // true
console.log(new String() instanceof String) // true

可以判断 对象的具体类型。

Object.prototype.toString.call()

console.log(Object.prototype.toString.call(123)) // [object Number]
console.log(Object.prototype.toString.call("123"))  // [object Boolean]
console.log(Object.prototype.toString.call(false)) // [object Number]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call([])) // [object Array]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call(function(){})) // [object Function]
console.log(Object.prototype.toString.call(new String)) // [object String]

类型判断函数封装

function type(target) {
    var template = {
        "[object Array]": "array",
        "[object Object]": "object",
        "[object Number]": "number - object",
        "[object Boolean]": "boolean - object",
        "[object String]": "string - object"
    };
    if (target === null) {
        return null;
    }
    if (typeof (target) == "object") {//引用值
        //数组 对象 包装类 Object.prototype.toString
        var str = Object.prototype.toString.call(target);
        return template[str];
    } else {//原始值 
        return typeof (target);
    }
}