JS学习笔记——标准对象
一、对象
在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'。
五、Date
1.在javascript中,Date对象用来表示日期和时间。
  var now = new Date();
  now; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)
  now.getFullYear(); // 2015, 年份
  now.getMonth(); // 5, 月份,注意月份范围是0~11,5表示六月
  now.getDate(); // 24, 表示24号
  now.getDay(); // 3, 表示星期三
  now.getHours(); // 19, 24小时制
  now.getMinutes(); // 49, 分钟
  now.getSeconds(); // 22, 秒
  now.getMilliseconds(); // 875, 毫秒数
  now.getTime(); // 1435146562875, 以number形式表示的时间戳 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号