Vue源码学习笔记之JavaScript数据类型

195 阅读1分钟

1.JavaScript的数据类型有几种?

答:JavaScript一共有7种数据类型。

(1)ES5中有6种数据类型:Undefined,Null,String,Number,Boolean,Object

其中Object包含的常用的引用类型有Date ,Array,Function

(2)ES6中新增了1种数据类型:Symbol

2.JavaScript的typeof方法返回值有几种?

答:六种:undefined,string,number,boolean,object,function

console.log(typeof null); //'object'      这个是js历史遗留问题,typeof将null作为object类型处理

console.log(typeof NaN); //'number'   NaN是一种特殊的Number类型;

console.log(typeof(fn)); //'function' 

3.vue源码里面的Object.prototype.toString的作用?

答:Object.prototype.toString可以精准的判断对象的类型。对于数组、null对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。要想区别对象、数组、函数单纯使用 typeof 是不行的,JavaScript中,通过Object.prototype.toString方法,判断某个对象值属于哪种内置类型。

console.log(Object.prototype.toString.call(123));       // [object Number] console.log(Object.prototype.toString.call('123'));     // [object String] console.log(Object.prototype.toString.call(undefined));     // [object Undefined] 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(function(){}));      // [object Function] console.log(Object.prototype.toString.call(null));      // [[object Null]]

var _toString = Object.prototype.toString; 

function toRawType (value) {

    return _toString.call(value).slice(8, -1) 

}

toRawType([1,2,3,4,5])   //  "Array"