JavaScript——数据类型

ECMAScript有5种基本数据类型Undefined ,Null ,Boolean ,Number ,String 和一种复杂类型 Object

1. Undefined

 Undefined类型只有一个值,即特殊的undefined

2. Null

  Null类型只有一个值,即特殊的null

  如果定义的变量准备用于保存对象,那么最好将该变量初始化为null,这样就知道该变量保存了一个对象的引用。

 注意:null 和 undefined 之间的相等操作符(==)总是返回true

3.Boolean

   Boolean类型只有两个值:true 和 false

   要将其他类型转换为Boolean,要调用转型函数Boolean(),任何非零数,任何除null以外的对象转为true,0和NaN,null,undefined转换为false

View Code
var m = "hello";
var mAsBoolean = Boolean(m);
var m1 = 2000;
var m1AsBoolean = Boolean(m1);
var m2 = new Object();
var m2AsBoolean = Boolean(m2);
var m3AsBoolean = Boolean(null);
var m4AsBoolean = Boolean(0);
var m5AsBoolean = Boolean(NaN);
var m6AsBoolean = Boolean(undefined);
alert("mAsBoolean = Boolean(m):" + mAsBoolean + "\n\r" +
      "m1AsBoolean= Boolean(m1) :" + m1AsBoolean + "\n\r" +
      "m2AsBoolean= Boolean(m2):" + m2AsBoolean + "\n\r" +
      "m3AsBoolean= Boolean(null):" + m3AsBoolean + "\n\r" +
      "m4AsBoolean= Boolean(0):" + m4AsBoolean + "\n\r" +
      "m5AsBoolean= Boolean(NaN) :" + m5AsBoolean + "\n\r" +
      "m6AsBoolean= Boolean(undefined):" + m6AsBoolean);

4.Number

   ECMAScript中,用IEEE754格式来表示整数和浮点数,因为Number()函数在转换字符串时比较复杂,而且不够合理,所以一般用parseInt(),parseFloat()

View Code
 var octnum = "070";
    var hexnum = "0xa";
    var intnum = 56;
    var floatNum = 1.389;
    var str = "hello";
    var str1 = "123hi";
    var str2 = "hello456";
    var str3 = "test789hi";
    alert("Number(octnum):" + Number(octnum) + "," + 'parseInt(octnum,8):' + parseInt(octnum, 8) + "," + 'parseInt(octnum)' +parseInt(octnum)+"\n\r" +
        "Number(hexnum):" + Number(hexnum) + "," + 'parseInt(hexnum,16):' + parseInt(hexnum, 16) + "," + 'parseInt(hexnum)' +parseInt(hexnum)+"\n\r" +
        "Number(intnum):" + Number(intnum) + "," + 'parseInt(intnum,10):' + parseInt(intnum, 10) + "," + 'parseInt(intnum)' +parseInt(intnum) +"\n\r" +
        "Number(floatNum):" + Number(floatNum) + "," + 'parseFloat(floatNum):' + parseFloat(floatNum) + "\n\r" +
        "Number(str):" + Number(str) + "," + 'parseInt(str):' + parseInt(str) + "," + 'parseFloat(str)' + parseFloat(str) + "\n\r" +
        "Number(str1):" + Number(str1) + "," + 'parseInt(str1):' + parseInt(str1) + "," + 'parseFloat(str1)' +parseFloat(str1)+ "\n\r" +
        "Number(str2):" + Number(str2) + "," + 'parseInt(str2):' + parseInt(str2) + "," + 'parseFloat(str2)' + parseFloat(str2)+"\n\r" +
        "Number(str3):" + Number(str3) + "," + 'parseInt(str3):' + parseInt(str3) + "," + 'parseFloat(str3)' + parseFloat(str3));

5. String

String 类型用于表示由零或多个16位的Unicode字符组成的字符序列,,字符串可以由双引号或单引号表示。

要把一个值转换为字符串,有两种方法:

1是每个值都有一个toString()方法,默认情况下toString()方法以10进制格式返回数值字符串,也可以传递基数。

例如: var num=100;num.toString(16);

2在不知道要转换的类型是不是null或undefined的情况下,可以用String()。

String()遵循的转换规则为:如果此值有toString()方法,就调用toString(),如何值为null,则返回“null”;如果值为undefined,则返回undefined

6 Object比较复杂,到时候单独拿出来总结

 

posted @ 2012-09-06 16:15  绿茶叶  阅读(1554)  评论(5编辑  收藏  举报