ps: 如果有任何问题可以评论留言,我看到后会及时解答,评论或关注,您的鼓励是我分享的最大动力
转载请注明出处:
https://blog.csdn.net/qq_40938301/article/details/104784040
一、Javascript 数据类型
6种基本类型:undefined、null、boolean、string、number 以及 ES6新增的 symbol
1种引用类型:object
(注:function 以及 array 都属于对象, function 是 Function()的实例,array 是 Array()的实例)
ps. symbol 是 ES6 新增的数据类型,作用是作为一个 独一无二 的标记,用于区别防止冲突。
基本类型:数据保存在 栈内存,数据大小固定
引用类型:数据保存在 堆内存,数据大小不固定,栈内存存着堆内存中数据内容的地址
二、typeof 和 instanceof 的区别
二者的功能都是用来判断 数据类型,但用法和效果不一样
1、typeof
用于判断数据类型,返回值为 string 类型:
undefined、boolean、symbol、number、string、function、object
(注:返回值并不完全等于 Javascript 的 7 种数据类型,多了个 function ,少了个 null)
而且 typeof( null ) 的值是 object,这属于 JavaScript 早期流传下来的 bug 。。而且现在貌似 ES6 中视其为 feature
eg:
var a = [1,2,3,4],
b = 56,
c = 'abcdefg',
d = function(){console.log('我是函数')},
e = true,
f = null,
g;
console.log(typeof(a)); //object
console.log(typeof(b)); //number
console.log(typeof(c)); //string
console.log(typeof(d)); //function
console.log(typeof(e)); //boolean
console.log(typeof(f)); //object
console.log(typeof(g)); //undefined
因为 typeof 在判断 null、array、object 时,得到的都是 object。这使得在判断这些数据类型的时候,
无法准确判断。所以引出 instanceof
2、instanceof
用于判断是否是 xxx(原型) 的实例,返回值为 boolean 类型
(注:基本数据类型没有原型)
eg:
var a = [], //array
b = {}, //object
c = function(){console.log('我是函数')}, //function
console.log(a instanceof Array); //true
console.log(b instanceof Object); //true
console.log(c instanceof Function); //true