DIV CSS 佈局教程網

JavaScript 資料型別實例大全:Number、String 與常用方法
編輯:JavaScript基礎知識     

前面我們介紹過 JavaScript 的資料型別,這次改用實例把重點再走一遍,希望能達到溫故知新的效果。

一、三種基本包裝型別

JavaScript 為三種基本型別提供了對應的包裝物件:Boolean、Number 與 String。實務上有個原則:盡量不要使用 Boolean 物件,因為它極易與基本型別的布林值混淆(例如 new Boolean(false) 是 truthy 的物件),直接用 true / false 就好。

二、Number:數字相關方法

toString(基数):轉成指定進位制的字串

var num = 10;
alert(num.toString());     // "10"
alert(num.toString(2));    // "1010"
alert(num.toString(8));    // "12"
alert(num.toString(10));   // "10"
alert(num.toString(16));   // "a"

toFixed():指定小數位數,含四捨五入

var num = 10;
num.toFixed(2);            // "10.00"

toExponential():科學記號表示法

接受一個參數,表示結果中小數的位數。

var num = 10;
alert(num.toExponential(1));   // "1.0e+1"

toPrecision():自動挑選最適合的格式

這麼小的數字其實用不到指數表示法。若想得到某個數值「最合適」的格式,應該用 toPrecision(),它可能回傳固定格式,也可能回傳指數格式。參數代表的是「整個數值的有效位數」(不含指數部分)。

var num = 99;
alert(num.toPrecision(1));   // "1e+2" —— 指數無法表示 99,於是無條件進位成 100
alert(num.toPrecision(2));   // "99"
alert(num.toPrecision(3));   // "99.0"

三、String:字串相關方法

String 物件的方法,在基本字串型別上也能直接呼叫——這是 JavaScript 自動包裝(auto-boxing)的結果。

1. 字元操作:charAt() 與 charCodeAt()

兩者都接受一個從 0 開始的位置索引,一個回傳該位置的「字元」,一個回傳該位置的「字元編碼」。

var stringValue = "Hello world!";
stringValue.charAt(1);      // "e"   第二個位置的字母是 e
stringValue.charCodeAt(1);  // 101   字母 e 的編碼是 101

2. 字串操作:concat、slice、substring、substr

這四個方法很容易搞混,關鍵在參數含義:slice 與 substring 的第二個參數是「結束位置」,而 substr 的第二個參數是「長度」。

var str1 = "hello";
alert(str1.concat(" word"));        // "hello word"
alert(str1.concat(" word", "!"));   // "hello word!"

var stringValue = "Hello world!";
alert(stringValue.slice(3));        // "lo world!"
alert(stringValue.substring(3));    // "lo world!"
alert(stringValue.substr(3));       // "lo world!"

alert(stringValue.slice(3, 7));     // "lo w"   擷取 3 ~ 7(不含 7)
alert(stringValue.substring(3, 7)); // "lo w"   同上
alert(stringValue.substr(3, 7));    // "lo worl" 從 3 開始取 7 個字元

另外要注意,slice() 允許傳入負數(從尾端起算),而 substring() 遇到負數會當成 0 處理,且會自動把兩個參數中較大的值擺到後面。

3. 位置查詢:indexOf() 與 lastIndexOf()

這兩個方法在字串中搜尋指定子字串,回傳其位置,找不到則回傳 -1。差別在搜尋方向:一個從頭往後找,一個從尾往前找。兩者都接受一個可選的第二參數,用來指定搜尋的起點。

var stringValue = "hello word";
alert(stringValue.indexOf("o"));      // 4
alert(stringValue.lastIndexOf("o"));  // 7

搭配迴圈反覆呼叫,就能找出所有出現位置:

var stringValue = "wo de wei lai bu shi meng! wo men you geng hao de ming tian!";
var positions = [];
var pos = stringValue.indexOf("e");

while (pos > -1) {
  positions.push(pos);
  pos = stringValue.indexOf("e", pos + 1);   // 從下一個位置繼續找
}

alert(positions);   // 4, 7, 22, 33, 38, 47

4. trim():去除前後空白

會建立一個字串副本,刪除前置與後置的所有空白(不影響原字串)。

var stringValue = "  hello word  ";
alert(stringValue);        // "  hello word  "
alert(stringValue.trim()); // "hello word"

5. 大小寫轉換

共有四個方法:toLowerCase()、toLocaleLowerCase()、toUpperCase()、toLocaleUpperCase()。帶 Locale 的版本會依地區規則處理特殊字母(例如土耳其文的 I),在多語系環境下較為穩妥。

var stringValue = "hello word";
alert(stringValue.toLocaleUpperCase());   // 較穩妥
alert(stringValue.toUpperCase());
alert(stringValue.toLocaleLowerCase());   // 較穩妥
alert(stringValue.toLowerCase());

6. 比對與替換:replace()

replace() 接受兩個參數:第一個是正規表達式或字串,第二個是替換字串或一個函數。注意若第一個參數傳字串,只會替換「第一個」符合項;要全部替換必須使用正規表達式並加上 g 旗標。

var text = "cat,bat,sat,fat";
alert(text.replace("at", "ond"));    // 只換第一個
alert(text.replace(/at/g, "ond"));   // 全部替換

// 也可以用 $1 反向引用捕獲群組
alert(text.replace(/(.at)/g, "word ($1)"));

第二個參數同樣可以是函數,這在做 HTML 轉義時特別好用:

function htmlEscape(text) {
  // 函數會收到三個參數:1. 符合整個模式的項目
  //                        2. 該項目在字串中的位置
  //                        3. 原始字串
  return text.replace(/[<>"&]/g, function (match, index, text) {
    switch (match) {
      case "<":  return "&lt;";
      case ">":  return "&gt;";
      case "&": return "&amp;";
      case '"':  return "&quot;";
    }
  });
}

alert(htmlEscape('<p class="greeting">Hello World!</p>'));
// <p class=&quot;greeting&quot;>Hello World!</p>

7. localeCompare():字典順序比較

以 A.localeCompare("B") 的形式呼叫,回傳值有三種情況:

  • A 在字母表中排在 B 之前 → 回傳負數(-1)
  • A 與 B 相等 → 回傳 0
  • A 在字母表中排在 B 之後 → 回傳正數(1)
var stringValue = "f";
alert(stringValue.localeCompare("d"));   // 1
alert(stringValue.localeCompare("f"));   // 0
alert(stringValue.localeCompare("z"));   // -1

比起直接用 >、< 比較字串,localeCompare() 的好處是會尊重地區排序規則,對中文、日文或帶變音符號的歐洲語言尤其重要。

8. fromCharCode():靜態方法

它與 charCodeAt() 剛好相反,用一組編碼組回字串:

alert(String.fromCharCode(104, 101, 108, 108, 111));   // "hello"

結語

最後補充兩點實務建議。第一,HTML 相關的字串方法(如 anchor()、link()、big())早已被標準標記為不鼓勵使用,請改用 DOM 建立元素並設定屬性。第二,若要處理 4 個位元組的字元(emoji、部分罕用漢字),上述以「位置」為參數的方法都可能切壞字元,ES6 之後應改用 codePointAt()、Array.from() 這類以「碼點」為單位的 API。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved