1、數據類型
JS的數據類型分為基本類型和引用類型
- 基本類型:String、Number、Boolean、Null、Undefined、Symbol(new in ES6)
- 引用類型:Object(Object、Array、Date、RegExp、Function)
基本類型,存儲在棧中,可以直接調用,引用類型存儲在堆中,棧中存引用(指向堆的地址)。
這里,簡單的對這些數據類型做個說明:
1、Symbol:ES6新增,表示永不相同的數
let sy = Symbol("a");
let sy2 = Symbol("a");
sy === sy2; // false;
2、Date:時間類型
* new Date() // 當前時間
* new Date(year, month, day, hours, minutes, seconds, milliseconds) // 指定年月日時分秒毫秒
* new Date(milliseconds) // 毫秒 1970-1-1 00:00:00 Universal Time, 1970-1-1 08:00:00 GMT+080
* new Date(date string) // 時間格式字符串
3、RegExp: 正則
直接量語法:/pattern/attributes
創建 RegExp 對象的語法:new RegExp(pattern, attributes);
pattern 指定正則表達式的字符串,eg:"[a-z]"。
attributes 【可選】包含屬性 "g"【全局匹配】、"i" 【忽略大小寫】和 "m"【多行匹配】
4、Function:函數
function a() {
console.log(1);
}
let b = function() {
console.log(1);
}
new Function('c', console.log(1));
2、利用typeof檢查類型
typeof 1; // "number"
typeof '1'; // "string"
typeof null; // "object"
typeof undefined; // "undefined"
typeof Symbol("a"); // "symbol"
typeof {}; // "object"
typeof []; // "object"
typeof new Date(); // "object"
typeof /[a-z]/i; // "object"
typeof function a(){}; // "function"
根據結果不難發現,null和引用類型,除了function以外,typeof的結果都是object。這些是需要單獨判斷的。
附:
- 在js的理念中,引用類型都是對象,function也應該是object,但是由于function有很多特別的地方,所以單獨拿出來了。
- null也是比較特殊的,雖然是基本數據類型,但是typeof是“object”,表示空的引用。
2、檢查null和除function外的數據類型
1、null
null沒有直接的檢查方法,但是可以利用以下思路來實現:
typeof null; // "object"
null == undefined; // true
!null; //true
利用這些特性,可得:
let b = null;
typeof b !== "undefined" && b == undefined; // true
2、利用object.constructor屬性進行判斷
constructor 屬性返回對創建此對象的數組函數的引用
let obj = {};
obj.constructor === Object; // true
let arr = {};
arr.constructor === Array; // true
let t = new Date;
t.constructor === Date; // true
let r = /[a-z]/;
r.constructor === RegExp; // true