Javascript參考型別之封裝類型(Boolean、Number、String)
[1]定義:基本封裝類型是特殊的參考型別。每當讀取一個基本類型值的時候,後台就會建立一個對應的基本封裝類型的對象,從而可能調用一些方法來操作這些資料。 e.g. var s1 = 'some text'; var s2 = s1.substring(2); //在上述過程中,實際上發生了三個步驟 var s1 = new String('some text'); //(1)建立String類型的一個執行個體 var s2 = s1.substring(2); //(2)在執行個體上調用指定的方法 s1 = null; //(3)銷毀這個執行個體 [注意]參考型別和基本封裝類型的主要區別是對象的生存期。使用new操作符建立的參考型別的執行個體,在執行流離開當前範圍之前都一直儲存在記憶體中。而自動建立的基本封裝類型的對象,則只存在於一行代碼的執行瞬間,然後立即被銷毀。這意味著我們不能在運行時為基本類型值添加屬性和方法。 var s1 = 'some text';s1.color = 'red';alert(s1.color);//undefined [2]顯式建立封裝類型的兩種方式: [2.1]Object方式[不建議使用] [2.1.1]var s = new Object('abc'); [2.1.2]var b = new Object(true); [2.1.3]var n = new Object(123); [2.2]建構函式方式[不建議使用] [2.2.1]var s = new String('abc'); [2.2.2]var b = new Boolean(true); [2.2.3]var n = new Number(123); [注意]使用new調用基本封裝類型的建構函式與直接調用同名的轉型函數是不一樣的 var value = '25';var number = Number(value);console.log(typeof number);//numbervar obj = new Number(value);console.log(typeof obj);//object [3]Boolean類型是與布爾值對應的參考型別,在布林運算式中使用Boolean對象容易造成誤解[不建議使用] [3.1]繼承的方法 [3.1.1]valueOf():返回基本類型值true 或 false [3.1.2]toString()和toLocaleString():返回字串'true' 或'false' [4]Number類型是與數字值對應的參考型別,在使用typeof和instance操作符時容易產生誤解[不建議使用] [4.1]繼承的方法 [4.1.1]valueOf():返回基本類型的數值 [4.1.2]toString()和toLocaleString():返回字串形式的數值 [tips]可以為toString()方法傳遞一個表示基數的參數
var num = 10;console.log(num.toString());//'10'console.log(num.toString(2));//'1010'console.log(num.toString(8));//'12'console.log(num.toString(10));//'10'console.log(num.toString(16));//'a'
[4.2]數值格式化為字串的方法 [4.2.1]toFixed():按照指定的小數位返回數值四捨五入後的字串表示(常用於處理貨幣值) [注意]toFixed()裡的參數只接受0-20,若不傳參則相當於參數是0 var num = 10.456;console.log(num.toFixed(2));//10.46console.log(num.toFixed());//10 [4.2.2]toExponential():返回指數標記法(e標記法)的數值的字串表示,參數表示轉換後的小數位元 [注意]toExponential()裡的參數只接受0-20,若不傳參則相當於不針對小數進行四捨五入 var num = 10.456;console.log(num.toExponential(2));//1.05e+1console.log(num.toExponential());//1.0456e+1 [4.2.3]toPrecision():接收一個參數,即表示數值的所有數位位元(不包括指數部分),自動調用toFixed()或toExponential() [注意]toFixed()裡的參數只接受1-21,若不傳參則不對原數字進行任何操作 var num = 10;console.log(num.toPrecision(3));//10.0console.log(num.toPrecision(2));//10 console.log(num.toPrecision(1));//1e+1console.log(num.toPrecision());//10 [5]String類型是與字串對應的參考型別 [5.1]length屬性:String類型的每個執行個體都有一個length屬性,表示字元的個數。該屬性只可讀取,不可改變 [5.2]繼承的方法:valueOf()、toString()和toLocaleString():返回字串表示 [5.3]訪問字元方法:接收一個基於0的字元位置的參數,並以單字元字串的形式返回 [5.3.1]charAt():返回給定位置的字元 [注意]當參數為空白時,預設參數為0;當參數超出範圍時,則什麼都不輸出 [5.3.2]中括弧加數字索引(ECMAScript5):返回給定位置的字元(IE7-不支援,輸出undefined) [注意]當參數為空白或參數超出範圍時,則輸出undefined [5.3.3]charCodeAt():返回給定位置的字元編碼,字元編碼為Number類型 [注意]當參數為空白時,預設參數為0;當參數超出範圍時,則輸出NaN [5.3.4]String.fromCharCode():把一個或多個編碼值轉成一個字串 [注意]參數範圍為ASCII表的範圍
var stringValue = 'hello world';console.log(stringValue.charAt(1));//'e'console.log(stringValue.charCodeAt(1));//101console.log(typeof stringValue.charCodeAt(1));//'number'console.log(String.fromCharCode(104,101,108,108,111));//'hello'console.log(String.fromCharCode(0x6211,0x662f,0x5c0f,0x706b,0x67f4));//'我是小火柴'console.log(stringValue[1]);//'e'
[5.4]字串拼接方法 [5.4.1]concat():可以接受任意多個參數,用於將一個或多個字串拼接起來,返回拼接得到的新字串 [5.4.2]+:加號操作符在多數情況下比concat()更簡便 var stringValue = 'hello ';console.log(stringValue.concat('world','!'));//'hello world!'console.log(stringValue + 'world' + '!');//'hello world!'[5.5]子字串建立方法:返回被操作字串的一個子字串,若無參數則返回原字串 [5.5.1]substr:接受兩個參數:子字串開始位置、子字串長度(可選,預設到原字串結束) [a1]當第一個參數為正數且大於等於原字串長度時,不輸出 [a2]當第一個參數為負數且絕對值小於原字串長時,相當於第一個參數+原字串長度之後的值 [a3]當第一個參數為負數且絕對值大於等於原字串長時,相當於第0個位置 [b1]當第二個參數為負數時,被置0 [b2]當第二個參數的值大於等於可以提供的字元個數時,以最大字元數輸出 [注意]IE8-在處理第一個參數為負值時存在問題,輸出原字串
var stringValue = 'hello world';console.log(stringValue.substr());//'hello world'console.log(stringValue.substr(2));//'llo world'console.log(stringValue.substr(20));//空console.log(stringValue.substr(-2,2));//'ld'console.log(stringValue.substr(-2,20));//'ld'console.log(stringValue.substr(-20,2));//'he'console.log(stringValue.substr(-20,-2));//空
[5.5.2]substring:接受兩個參數:子字串開始位置、子字串結束後一位的位置(可選,預設為原字串長度) [a1]當有參數為負數時,被置0 [b1]若第二個參數小於第一個參數,則替換位置 [b2]若第二個參數大於第一個參數或者第二個參數不存在時,第一個參數大於原字串長度時,無輸出 [b3]若第二個參數大於等於字串長度時,等於字串長度
var stringValue = 'hello world';console.log(stringValue.substring());//'hello world'console.log(stringValue.substring(2));//'llo world'console.log(stringValue.substring(20));//空console.log(stringValue.substring(-2,2));//'he'console.log(stringValue.substring(-2,20));//'hello world'console.log(stringValue.substring(-20,2));//'he'console.log(stringValue.substring(-20,-2));//空
[5.5.3]slice:接受兩個參數:子字串開始位置、子字串結束後一位的位置(可選,預設為原字串長度) [a1]當參數為負數且絕對值小於原字串長時,相當於參數+原字串長度之後的值 [a2]當參數為負數且絕對值大於等於原字串長時,相當於第0個位置 [b1]當第一個參數為正數且大於等於原字串長度時,不輸出 [b2]當第一個參數大於等於第二個參數不輸出 [c1]若第二個參數大於等於字串長度時,等於字串長度
var stringValue = 'hello world';console.log(stringValue.slice());//'hello world'console.log(stringValue.slice(2));//'llo world'console.log(stringValue.slice(20));//空console.log(stringValue.slice(-2,2));//空console.log(stringValue.slice(-2,-20));//空 console.log(stringValue.slice(-2,20));//'ld'console.log(stringValue.slice(-20,2));//'he'console.log(stringValue.slice(-20,-2));//'hello wor'
[總結] [a]substr:子串長度為負則置0 [b]substring:參數為負則置0,大小要調換 [c]slice:不置0,不調換 [5.6]字串位置方法:兩個參數:要尋找的子字串、表示尋找起點位置的索引(可選)。返回第一個滿足條件的子字串在字串中的位置,如果沒有找到則返回-1(位置方法不會影響原字串)[注意]傳回值是Number類型 [5.6.1]indexOf:從左至右搜尋 [5.6.2]lastIndexOf:從右至左搜尋 var string = 'hello world world';console.log(string.indexOf('ld',10));//15console.log(string.lastIndexOf('ld',10));//9 [tips]尋找出字串所有合格子字串
function allIndexOf(str,value){ var result = []; var pos = str.indexOf(value); while(pos > -1){ result.push(pos); pos = str.indexOf(value,pos+value.length); } return result;}console.log(allIndexOf('helllhelllhelll','ll'));//[2,7,12];
[5.7]trim()(ECMAScript5):返回刪除前置及尾碼空格的字串副本var string = ' hello world ';console.log(string.trim());//'hello world'; [tips1]可以用trim()來判斷輸入的字元是否為空白if(usename.trim().length){ alert('correct');}else{ alert('error');} [tips2]用正則類比trim();function fnTrim(str){ return str.replace(/^\s+|\s+$/,'')} console.log(fnTrim(' hello world '));//'hello world'[5.8]大小寫轉換方法 [5.8.1]toUpperCase():全部轉換成大寫 [5.8.2]toLowerCase():全部轉換成小寫 [5.8.3]toLocaleUpperCase():全部轉換成大寫(針對地區) [5.8.4]toLocaleLowerCase():全部轉換成小寫(針對地區) [注意]在不知道自己的代碼將在哪個語言環境中啟動並執行情況下,使用針對地區的方法更穩妥var string = 'Hello World';console.log(string.toLowerCase());//hello worldconsole.log(string.toLocaleLowerCase());//hello worldconsole.log(string.toUpperCase());//HELLO WORLDconsole.log(string.toLocaleUpperCase());//HELLO WORLD [tips]大小寫轉換方法可以連續使用 e.g. console.log((string.toUpperCase()).toLowerCase());//hello world[5.9]模式比對方法 [5.9.1]match():只接受一個參數,正則或字串,把匹配的內容儲存到一個數組中返回 [注意]加上全域標記時,match()方法傳回值中沒有index和input屬性 [a]不加/gvar string = 'cat,bat,sat,fat';var pattern = /.at/;var matches = string.match(pattern);console.log(matches,matches.index,matches.input);//['cat'] 0 'cat,bat,sat,fat' [b]加/gvar string = 'cat,bat,sat,fat';var pattern = /.at/g;var matches = string.match(pattern);console.log(matches,matches.index,matches.input);//['cat','bat','sat','fat'] undefined undefined [c]字串var string = 'cat,bat,sat,fat';var pattern = 'at';var matches = string.match(pattern);console.log(matches,matches.index,matches.input);//['at'] 1 'cat,bat,sat,fat' [5.9.2]search():只接受一個參數,正則或字串,返回匹配的內容在字串中首次出現的位置,類似於不能設定起始位置的indexOf,找不到返回-1 [a]正則(加/g和不加/g效果一樣)var string = 'cat,bat,sat,fat';var pattern = /.at/;var pos = string.search(pattern);console.log(pos);//0 [b]字串var string = 'cat,bat,sat,fat';var pattern = 'at';var pos = string.search(pattern);console.log(pos);//1
[tips]找出匹配的所有位置
function fnAllSearch(str,pattern){ var pos = str.search(pattern); var length = str.match(pattern)[0].length; var index = pos+length; var result = []; var last = index; result.push(pos); while(true){ str = str.substr(index); pos = str.search(pattern); if(pos === -1){ break; } length = str.match(pattern)[0].length; index = pos+length; result.push(last+pos); last += index; } return result;} console.log(fnAllSearch('cat23fbat246565sa3dftf44at',/\d+/));//[3,9,17,22]
[5.9.3]replace():接收兩個參數:第一個參數為Regex或字串(待尋找的內容)、第二個參數為字串或函數(替換的內容) [a]字串替換var string = 'cat,bat,sat,fat';var result = string.replace('at','ond');console.log(result);//'cond,bat,sat,fat' [b]正則無/g替換var string = 'cat,bat,sat,fat';var result = string.replace(/at/,'ond');console.log(result);//'cond,bat,sat,fat' [c]正則有/g替換var string = 'cat,bat,sat,fat';var result = string.replace(/at/g,'ond');console.log(result);//'cond,bond,sond,fond'
[d]函數替換:在只有一個匹配項(即與模式比對的字串的情況下,會向這個函數傳遞3個參數:模式的匹配項、模式比對項在字串中的位置、原始字串。在Regex定義了多個擷取的群組的情況下,傳遞給函數的參數依次是模式的匹配項、第一個擷取的群組的匹配項、第二個擷取的群組的匹配項……第N個擷取的群組的匹配項,但最後兩個參數仍然分別是模式的匹配項在字串中的位置和原始字串,這個函數返回一個字串。
function htmlEscape(text){ return text.replace(/[<>"&]/g,function(match,pos,originalText){ switch(match){ case '<': return '<'; case '>': return '>'; case '&': return '&'; case '\"': return '"'; } });}console.log(htmlEscape('<p class=\"greeting\">Hello world!</p>'));//<p class=" greeting">Hello world!</p>console.log(htmlEscape('<p class="greeting">Hello world!</p>'));//同上
[tips]關於$符號的用法
//$$ $//$& 匹配整個模式的子字串(與RegExp.lastMatch的值相同)//$` 匹配子字串之前的子字串(與RegExp.leftContext的值相同)//$' 匹配子字串之後的子字串(與RegExp.rightContext的值相同)//$n 匹配第n個擷取的群組的子字串,其中n等於0-9。$1表示匹配第一個擷取的群組的子字串(從第1個算起)//$nn 匹配第nn個擷取的群組的子字串,其中nn等於01-99
console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$0'))//$0,$0,$0,$0 console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$1'))//ca,ba,sa,faconsole.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$2'))//t,t,t,tconsole.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$3'))//$3,$3,$3,$3 console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$$'))//$,$,$,$console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$&'))//cat,bat,sat,fatconsole.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,'$`'))//,cat,,cat,bat,,cat,bat,sat,console.log('cat,bat,sat,fat'.replace(/(.a)(t)/g,"$'"))//,bat,sat,fat,,sat,fat,,fat,
[5.9.4]split():基於指定的分隔字元將一個字串分割成多個字串,並將結果放在一個數組中,分隔字元可以是字串,也可以是一個RegExp,該方法可以接受第二個參數(可選)用於指定數組的大小 [注意1]如果第二個參數為0-array.length範圍內的值時,按照指定參數輸出。其他情況將所有結果都輸出。 [注意2]IE8-對split()中Regex,會忽略擷取的群組 [tips]如果是split(''),則原來的數組會一個字元字元分割後傳出來
var colorText = 'red,blue,green,yellow';console.log(colorText.split(','));//["red", "blue", "green", "yellow"]console.log(colorText.split(',',2));//["red", "blue"]console.log(colorText.split(/\,/));//["red", "blue", "green", "yellow"]console.log(colorText.split(/e/));//["r", "d,blu", ",gr", "", "n,y", "llow"]console.log(colorText.split(/[^\,]+/));//將除去逗號以外的字串變為分隔字元["", ",", ",", ",", ""],IE8及以前會識別為[",",",",","]
[5.10]字串比較方法localeCompare():用於比較兩個字串,如果字串在字母表中排在字串參數之前,則返回一個負數(大多數情況下為-1);如果字串等於字串參數,則返回0;如果字串在字母表中排在字串參數之後,則返回一個正數(大多數情況下為1) [注意]在ASCII表中,大寫字母排在小寫字母前面
var stringValue = 'yellow';console.log(stringValue.localeCompare('brick'));//1 'y'> 'b'console.log(stringValue.localeCompare('yellow'));//0 'yellow' == 'yellow'console.log(stringValue.localeCompare('zoo'));//-1 'yellow' < 'zoo'