JS中的数据类型
1、数据类型
值类型(基本类型):字符串(String)、数字(Number)、布尔(Boolean)、空(Null)、未定义(Undefined)、Symbol、bigint 。
引用数据类型:Object(包括Array,Function、Object类等)。JavaScript中可以说一切皆对象。
区别:前七种原生数据类型的存放在栈中,引用数据类型存放在堆中,它的地址在栈中,一般我们访问就是它的地址。
console.log(typeof 123); //number console.log(typeof "abc"); //string console.log(typeof true); //boolean console.log(typeof null); //object console.log(typeof undefined); //undefined console.log(typeof [1, 2, 3]); //object console.log(typeof {a:123,b:456}); //object console.log(typeof function a(){return 123}); //function 实际上,在判断引用类型时,除了function其他的都为object
可参考:http://www.runoob.com/js/js-datatypes.html
1.1、JS中Null与Undefined的区别
区别:
- Undefined类型只有一个值,即undefined。当声明的变量还未被初始化时,变量的默认值为undefined。undefind 是全局对象的一个属性,当一个变量没有被赋值或者一个函数没有返回值或者某个对象不存在某个属性却去访问或者函数定义了形参但没有传递实参,这时候都是undefined。
- Null类型也只有一个值,即null。null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象。
var val; val== undefined //输出 "true" 这段代码显示为true,代表 val 的值即为undefined,因为我们没有初始化它。 null == document.getElementById('notExistElement') // 当想要获取页面上一个不存在的DOM节点时,这段代码显示为"true",因为我们尝试获取一个不存在的对象。
alert(typeof undefined); //output "undefined" alert(typeof null); //output "object"
第一行代码很容易理解,undefined的类型为Undefined;第二行代码却让人疑惑,为什么null的类型是Object?其实这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来。在今天我们可以解释为,null即是一个不存在的对象的占位符,但是在实际编码时还是要注意这一特性。
alert(null == undefined); //output "true"
ECMAScript认为undefined是从null派生出来的,所以把它们定义为相等的。但是,如果在一些情况下,我们一定要区分这两个值,那应该怎么办呢?可以使用下面的两种方法。
alert(null === undefined); //output "false" alert(typeof null == typeof undefined); //output "false"
使用typeof方法在前面已经讲过,null与undefined的类型是不一样的,所以输出"false"。而===代表绝对等于,在这里null === undefined输出false。
2、判断数据类型
2.1、判断是否为对象
var obj = {a: 123, b: 456} console.log(Object.prototype.toString.call(obj) === '[object Object]'); //true console.log(obj.constructor === Object); //true console.log(obj instanceof Object); //true
2.2、判断是否为数组
var obj = [1,2] console.log(Array.isArray(obj)); //true console.log(obj instanceof Array); //true console.log(Object.prototype.toString.call(obj) === '[object Array]'); //true console.log(obj.constructor === Array); //true console.log(obj.push != undefined); //true 有兼容性问题
2.3、判断是否为字符串
var str = 'aaa' console.log(typeof str); //string console.log(str.constructor); //ƒ String() { [native code] } console.log(Object.prototype.toString.call(str)); //[object String] var str2 = new String(); console.log(str2 instanceof String); //true 只有通过new方式声明一个字符串时,使用instanceof方法才是true