判断数据类型的方法
var red = "shark";
var orange = 123456;
var yellow = true;
var green = undefined;
var cyan = null;
var blue = ['a','s','d'];
var magenta = {};
var purple = function(){};
var black = [red,orange,yellow,green,cyan,blue,magenta,purple];
- Array.isArray():只能判别Array数据类型
console.log(Array.isArray(blue));
- instanceof:只能判别Function、Object、Array
console.log(purple instanceof Function);
console.log(magenta instanceof Object);
console.log(blue instanceof Array);
- typeof:不能判别null,Array,Object数据类型,返回值都是Object
for(var i=0;i<black.length;i++){
console.log(typeof black[i]);
}
- Object.prototype.toString.call():数据类型判别最佳方案
for(var i=0;i<black.length;i++){
console.log(Object.prototype.toString.call(black[i]));
}