标签:
一、对象
在js中万物皆对象。
二、对象类型
number、string、boolean、undefined、function、object等
用typeof来获取对象的类型
如:
alert( typeof 123 ); //number
alert( typeof NaN ); //number
alert( typeof ‘str‘ ); //string
alert( typeof true ); //boolean
alert( typeof undefined ); //undefined
alert( typeof Math.abs ); //function
alert( typeof null ); //object
alert( typeof [] ); //object
alert( typeof {} ); //object
三、包装对象
1.包装对象
number、boolean、string都有包装对象,包装对象用new创建。包装对象后,值不变,但是类型都变为object。
如:
var num = new Number(123);
var bool = new Boolean(true);
var str = new String(‘abc‘);
最好不要使用包装对象,尤其是string类型。
2.在使用Number、Boolean、String时,没有使用new,此时只是相当于数据类型转换。
var num = Number(‘123‘); //123,相当于parseInt()或parseFloat()
alert( typeof num ); //number
var bool = Boolean(‘true‘); //true
alert( typeof bool ); //boolean
var bool2 = Boolean(‘false‘); //true 非空字符串都是true
var bool3 = Boolean(‘‘); //false
var str = String(123.45); //‘123.45‘
alert( typeof str ); //string
四、需要注意的点
不要使用new Number()
、new Boolean()
、new String()
创建包装对象;
用parseInt()
或parseFloat()
来转换任意类型到number
;
用String()
来转换任意类型到string
,或者直接调用某个对象的toString()
方法(null和undefined没有该方法;number对象使用toString()方法需要特殊处理:123..toString();或(123).toString(););
通常不必把任意类型转换为boolean
再判断,因为可以直接写if (myVar) {...}
;
typeof
操作符可以判断出number
、boolean
、string
、function
和undefined
;
判断Array
要使用Array.isArray(arr)
;
判断null
请使用myVar === null
;
判断某个全局变量是否存在用typeof window.myVar === ‘undefined‘
;
函数内部判断某个变量是否存在用typeof myVar === ‘undefined‘
。
标签:
原文地址:http://www.cnblogs.com/liyo/p/4760882.html