JS中一共有七种数据类型:
一种引用类型——Object(Date Array Error Function Math ),
六种基本数据类型——Number、String、Boolean、Null、Undifined、Symbol(ES6新增)
typeof(var):返回的是一个字符串,但是对于复杂数据类型来说,不管是数组Array、日期Date
或者是普通对象,这种方法返回的都是Object,无法更详细的区分。
console.log(typeof 2); // number
console.log(typeof true); // boolean
console.log(typeof 'str'); // string
console.log(typeof []); // object []数组的数据类型在 typeof 中被解释为 object
console.log(typeof function(){}); // function
console.log(typeof {}); // object
console.log(typeof undefined); // undefined
console.log(typeof null); // object null 的数据类型被 typeof 解释为 object
(var) instranceof (type):但是这种方法在iframe下会产生bug,而且这种方法也无法准确判断Function和Object的类型,
因为既可以说函数是个构造方法,也可以说方法是一个对象。
console.log(2 instanceof Number); // false
console.log(true instanceof Boolean); // false
console.log('str' instanceof String); // false
console.log([] instanceof Array); // true
console.log(function(){} instanceof Function); // true
console.log({} instanceof Object); // true
基本数据类型挂掉 因为在这里字面量值,2, true ,'str'不是实例,所以判断值为false
在他的要求中 判断一个对象是否是数据类型的实例
除非写成 console.log(new Number(2) instanceof Number);// true
浏览器认为null,undefined不是构造器。判断null和undefined时候控制台异常
(var).Constructor (type):这种方法在类继承的时候同样有可能产生bug,继承者必须指定自己的Constructor。
console.log((2).constructor === Number);
console.log((true).constructor === Boolean);
console.log(('str').constructor === String);
console.log(([]).constructor === Array);
console.log((function() {}).constructor === Function);
console.log(({}).constructor === Object);
bug情况
function Fn(){};
Fn.prototype=new Array();
var f=new Fn();
console.log(f.constructor===Fn); // false
console.log(f.constructor===Array); // true
Object.prototype.toString.call(var) == ‘[Object (type)]’:完美。
var a = Object.prototype.toString;
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function(){}));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));
类型转化大致上的经常需要转化的有三种:num str bool;
一:转化
1.隐式转化:
这个就跳过了,注意+ - null就可以了
2.显示转化:
toString()
parseInt()
parseFloat()
3.强制转化:
boolean()
string()
number()
二:判断
isNaN() 判断是非数字值
typeof(XX)=="string" 利用typeof来配合使用
你的对象 instanceof 类型
例如:
var oStringObject = new String("hello world");
console.log(oStringObject instanceof String);
json:在交互里面很常见,下面开始
json.parse:json字符串转化json对象,一定要是合法合理的json字符串‘{}’
json.stringify:将json对象转化json字符串,一定要是合法合理的json对象,因为会检测json对象格式,不符合要求会报错,不同于eval(),这个eval()不够严密,会有一定的数据传输问题,一旦被攻击注入,就挂了。所以少用eval()