码迷,mamicode.com
首页 > Web开发 > 详细

JS学习笔记——标准对象

时间:2015-08-26 17:29:22      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

一、对象

  在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操作符可以判断出numberbooleanstringfunctionundefined

  • 判断Array要使用Array.isArray(arr)

  • 判断null请使用myVar === null

  • 判断某个全局变量是否存在用typeof window.myVar === ‘undefined‘

  • 函数内部判断某个变量是否存在用typeof myVar === ‘undefined‘

JS学习笔记——标准对象

标签:

原文地址:http://www.cnblogs.com/liyo/p/4760882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!