一即碗、JavaScript中的數(shù)據(jù)類型
JS中的數(shù)據(jù)類型分為以下七類:
- 6 種原始類型:
- Boolean
- Null
- Undefined
- Number
- String
- Symbol (ECMAScript 6 新定義)
- 和 Object(復(fù)雜類型)
Object又分為: - Function
- Array
- Date
- RegExp
二、typeof
操作符
typeof true; // 'boolean';
typeof null; // object
typeof undefined; // undefined
typeof 1; // number
typeof ''; // string
typeof Symbol(); // 'symbol';
typeof []; // object
typeof {}; // object
三卢肃、如何區(qū)分?jǐn)?shù)組和對(duì)象
從上面的結(jié)果可知typeof
無(wú)法區(qū)分?jǐn)?shù)組和對(duì)象荠割∮缴荆總結(jié)一些下面的方法來(lái)區(qū)分它們秦士。
- typeof加length屬性
數(shù)組有l(wèi)ength屬性马昙,object沒有榄檬。
let arrayDeal = ['red', 'green'];
let objectDeal = {'blue', 'yellow'};
function getType (test) {
if(typeof o == 'object'){
if( typeof o.length == 'number' ){
return 'Array';
}else{
return 'Object';
}
}else{
return 'param is no object type';
}
}
instanceof
({}) instanceof Object; // true
([]) instanceof Array; // true
但數(shù)組也是屬于object卜范,因此我們要利用instanceof判斷數(shù)據(jù)類型是對(duì)象還是數(shù)組時(shí)應(yīng)該優(yōu)先判斷array,最后判斷object鹿榜。
-
isArray
Array.isArray() 該方法適用于確定傳遞的值是否為Array海雪。
Array.isArray([1, 2, 3]); // true
Array.isArray({foo: 123}); // false
Object.prototype.toString.call()
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [o
因?yàn)榉祷刂凳亲址钥梢杂?code>.slice(8, -1)方法去掉[object
和]
。
var getType = function (elem) {
return Object.prototype.toString.call(elem).slice(8, -1);
},