2008年12月17日

String 及其特徵

特徵 | 方法
String | prototype | fromCharCode | constructor | length
String

產生字串物件。其語法是:

new String()

new String(字串)

字串可用 ' ' 或 " " 包夾。String() 可當函式使用(不加 new),產生基本字串。

  • 程式用法:

    <script type='text/javascript'>
    var s1=new String('字串一');
    var s2=String('字串二');
    var s3='字串三';
    document.write( typeof s1 +' '+ s1 +'<br />');
    document.write( typeof s2 +' '+ s2 +'<br />');
    document.write( typeof s3 +' '+ s3 +'<br />');
    </script>

  • 執行結果:

    object 字串一
    string 字串二
    string 字串三

基本字串也可以使用字串物件的特徵與方法,javascript 會先產生一個暫時的物件,存放基本字串;然後用暫時物件執行方法;執行完後,會自動刪去暫時物件。

  • 程式用法:

    <script type='text/javascript'>
    document.write( s3.length );
    </script>

  • 執行結果:

    3

可以把字串當作陣列讀取,但是不能當作陣列存。

  • 程式用法:

    <script type='text/javascript'>
    s2[1]='b';
    for(var i=0; i < s2.length; i++)
      document.write( s2[i] +' : ');
    </script>

  • 執行結果:

    字 : 串 : 二 :

兩個字串可以用比較器作比較。

  • 程式用法:

    <script type='text/javascript'>
    var s4=new String('比較');
    var s5='比較';
    document.write( s4 == s5 );
    </script>

  • 執行結果:

    true

String 的特徵與方法

String 繼承了 Function.prototypeObject.prototype 的特徵與方法;這些可以直接用在 String,如同下面的用法,在此不再敖述。前述繼承的特徵與方法,有些只能用在物件型態,有些只能用在物件實體,有些兩者皆可;使用時要注意。

下述特徵必須與 String 配合使用,不能用在物件實體。

prototype

可以增加物件的特徵與方法。

  • 程式用法:

    <script type='text/javascript'>
    String.prototype.dump=function()
      {
        for(var i=0; i< this.length; i++)
         document.write( this[i] +' : ');
      }
    s3.dump();
    </script>

  • 執行結果:

    字 : 串 : 三 :

fromCharCode()

將一序列的獨角碼或 ASCII 碼轉換成基本字串。其語法是:

String.fromCharCode(字碼1, ..., 字碼N)

  • 程式用法:

    <script type='text/javascript'>
    var s6=String.fromCharCode(0x3041, 0x3042, 0x3043, 0x37, 0x38);
    document.write( s6 );
    </script>

  • 執行結果:

    ぁあぃ78

有一部分獨角碼大於 0xFFFF,要用兩個數值表示,可用下面的方法組成。

  • 程式用法:

    <script type='text/javascript'>
    function uniString(copt)
    {
      if(copt > 0xffff)
      {
        copt-=0x10000;
        return String.fromCharCode( 0xD800 +
               (copt >> 10), 0xDC00 + (copt & 0x3FF) );
      }
      else
        return String.fromCharCode( copt );
    }
    document.write( uniString( 0x13041 ) );
    </script>

  • 執行結果:

    𓁁

String 物件實體的特徵
constructor

存有產生物件實體的函式其位置。

  • 程式用法:

    <script type='text/javascript'>
    Jolin='蔡依林';
    document.write( Jolin.constructor );
    </script>

  • 執行結果:

    function String() { [native code] }

length

存有字串的長度。請注意,是字的個數,不是位元組(byte)的長度。獨角碼一個字可能有兩個或四個位元組。

  • 程式用法:

    <script type='text/javascript'>
    Jolin='蔡依林';
    document.write( Jolin.length );
    </script>

  • 執行結果:

    3


©2008-2009 by ant2legs, All Rights Reserved. ant2legs 擁有其製作的文章,圖片與程式的著作權,所有權利保留。