Javascript 引用類型(Boolean Number String)

基本包裝類型

我們會(huì)經(jīng)常對(duì)基本類型值作如下操作:

var str = "string";
str.substring(2); // "ring"

基本類型不是對(duì)象,沒有屬性和方法,那substring()是從哪里來(lái)的呢?
原來(lái)我們?cè)趫?zhí)行第二行時(shí),后臺(tái)會(huì)自動(dòng)完成如下過(guò)程:

var s1 = new String("string");
var s2 = s1.substring(2);
s1 = null;

Boolean類型

Boolean類型是與布爾值相對(duì)應(yīng)的引用類型。

var falsy= new Boolean(false);
truth.valueOf(); // false
truth.toString(); // "false"
falsy&& true; // true
Boolean(falsy); //true

由于falsy是一個(gè)對(duì)象,因此轉(zhuǎn)化為布爾值時(shí)為true

Number 類型

Number類型是與數(shù)值對(duì)應(yīng)的引用類型。

var num = 10;
num.valueOf(); //12
num.toString(); // "12" 
num.toString(2); // "1100"
toFixed()

toFixed()可以按照指定的小數(shù)位數(shù)返回?cái)?shù)值的字符串表示,如果指定的小數(shù)位數(shù)小于原有位數(shù),則四舍五入。

var num = 10.252;
num.toFixed(6); // "10.252000"
num.toFixed(2); // "10.25"
num.toFixed(1); // "10.3"
toExponential()

toExponential()可以將數(shù)值轉(zhuǎn)化為具有指定小數(shù)位數(shù)的科學(xué)技術(shù)法。

var num = 1234567;
num.toExponential(2); // "1.23e+6"
toPrecision()

toPrecision()可以格式化數(shù)值,傳入希望輸出的數(shù)值位數(shù)(計(jì)算位數(shù)時(shí)不考慮指數(shù))。

var num = 99;
num.toPrecision(1); // "1e+2"
num.toPrecision(3); // "99.0"

String 類型

String類型是與字符串相對(duì)應(yīng)的引用類型。

var str = "string";
str.toString(); // "string"
str.valueOf(); // "string"
str.length; // 6

每個(gè)String實(shí)例都有length屬性,表示一個(gè)字符串中包含的字符量,注意字符串中的雙字節(jié)字符視為一個(gè)字符。

訪問(wèn)特定位置的字符
  • charAt()
    接受一個(gè)參數(shù),表示要訪問(wèn)的字符在字符串中基于0的位置,返回指定位置的單字符字符串(ECMAScript中沒有單字符類型)
var str = "name";
console.log(str.charAt(2)); // "m"
  • charCodeAt()

接受一個(gè)參數(shù),表示要訪問(wèn)的字符在字符串中基于0的位置,返回指定位置的字符對(duì)應(yīng)的字符編碼字符串(ECMAScript中沒有單字符類型)

var str = "name";
console.log(str.charCodeAt(2)); // "109"
  • []
    在IE8、Firefox、Safari、Chrome、Opera瀏覽器中,還支持方括號(hào)訪問(wèn)個(gè)別字符的語(yǔ)法:
var str = "name";
console.log(str[2]); // "m"
字符串操作方法
  • concat()
    用于將一個(gè)或多個(gè)字符串拼接起來(lái)形成一個(gè)新的字符串。
var str1 = "Hello";
var str2 = "World";
str1.concat(" ", str2, "!"); // "Hello World"
str1; // "Hello"
  • +
    concat的功能相同,但更加簡(jiǎn)便。
"Hello" + " " + "World" + "!"; // "Hello World"
  • slice() substr() substring()
    這三個(gè)方法都可以基于子字符串返回新字符串,都接受1個(gè)或2個(gè)參數(shù),第一個(gè)都表示子字符串的起始位置,slice()substring()的第二個(gè)參數(shù)指定子字符串最后一個(gè)字符后面的位置,substr的第二個(gè)參數(shù)指定的是字符個(gè)數(shù),這三個(gè)方法對(duì)原始字符串不會(huì)產(chǎn)生影響。
var str = "Hello World!"; 
console.log(str.slice(3)); // "lo World!"
console.log(str.substr(3)); // "lo World!"
console.log(str.substring(3)); // "lo World!"
console.log(str.slice(3, 6)); // "lo "
console.log(str.substr(3, 6)); // "lo Wor"
console.log(str.substring(3, 6)); // "lo "

以上的例子傳入的參數(shù)均是正值,如果傳入負(fù)值,它們的表現(xiàn)就不會(huì)那么一致了。

var str = "Hello World!"; 
console.log(str.length);
console.log(str.slice(-3)); // "ld!" -3 被轉(zhuǎn)換成9
console.log(str.slice(9)); // "ld!"
console.log(str.substr(-3)); //"ld!" -3 被轉(zhuǎn)換成9
console.log(str.substr(-3)); // "ld!"
console.log(str.substring(-3)); // "Hello World!" -3被轉(zhuǎn)換成0
console.log(str.substring(0)); // "Hello World!"
console.log(str.slice(3, -8)); /  / "l" -8 被轉(zhuǎn)換為4
console.log(str.slice(3, 5)); // "l"
console.log(str.substr(3, -8)); // "" -8 被轉(zhuǎn)換為0
console.log(str.substr(3, -8)); // ""
console.log(str.substring(3, -10)); // "Hel" -10被轉(zhuǎn)化為0,由于0<3,0成為第一參數(shù)
console.log(str.substring(0, 3)); // "Hel"

如果slice()的參數(shù)為負(fù)值,它會(huì)使用字符串長(zhǎng)度與它們相加,如果相加后的結(jié)果為正,則返回相應(yīng)子字符串,如果結(jié)構(gòu)為負(fù),則轉(zhuǎn)換為0。
substr()slice()對(duì)待第一個(gè)參數(shù)的方式相同,當(dāng)substr()的第二個(gè)參數(shù)也為負(fù)值時(shí),它會(huì)直接將這個(gè)負(fù)值轉(zhuǎn)換為0。
substring會(huì)將小于0的參數(shù)都轉(zhuǎn)換為0,然后比較兩個(gè)參數(shù)的大小,最后將較小的參數(shù)作為第一個(gè)參數(shù),較大的參數(shù)作為第二個(gè)參數(shù)。

  • trim()
    創(chuàng)建一個(gè)字符串的副本(不影響原字符串),刪除前置和后綴空格。
    IE 9+、Safari 5+、Firefox 3.5+、Opera 10.5+、Chrome都支持這個(gè)方法,chrome 8+、Firefox 3.5+、Safari 5+還支持trimLeft()trimRight(),分別用于刪除字符串開頭和末尾的空格。
訪問(wèn)指定位置的字符串
  • indexOf(str, index)
    從字符串開頭搜索給定字符串str,返回子字符串的位置,如果沒有搜到,返回-1, index表示開始搜索的位置。
  • lastIndexOf(str, index)
    從字符串尾部搜索給定字符串str,返回子字符串的位置,如果沒有搜到,返回-1,index表示開始搜索的位置。
    書中提到了一個(gè)可以遍歷字符串,找到所有匹配子字符串的方法:
var str = "abcdabcabcdefabcddabcedfsd";
var position = new Array();
var pos = str.indexOf("d");
while(pos > -1) {
  position.push(pos);
  pos = str.indexOf("d", pos + 1);
}
console.log(position); // [3, 10, 16, 17, 22, 25]
大小寫轉(zhuǎn)換

toLowerCase() toUpperCase() toLocaleUpperCase() toLocaleLowerCase()

模式匹配
  • match()
    與之前提到過(guò)的RegExp.exec()本質(zhì)是一樣的,接受的參數(shù)要么是正則表達(dá)式,要么是RegExp對(duì)象,返回一個(gè)數(shù)組,數(shù)組第一項(xiàng)是匹配項(xiàng),之后是捕獲組匹配的字符串。
var str = "abcdabc";
var pattern = /ab(c)/;
str.match(pattern); // ["abc", "c", index: 0, input: "abcdabc"]
  • seach()
    接收正則表達(dá)式或RegExp對(duì)象,返回字符串中從開頭查找到的第一個(gè)匹配項(xiàng)的索引,如果找不到,返回-1。
var str = "abc";
var pattern = /a/;
str.search(pattern); // 0
  • replace()
    接受兩個(gè)參數(shù),第一個(gè)表示需要匹配的字符串或正則表達(dá)式,第二個(gè)表示要替換成的內(nèi)容,可以是字符串或函數(shù),如果第一個(gè)參數(shù)是字符串,只會(huì)替換掉第一個(gè)匹配的內(nèi)容,如果要替換所有匹配的內(nèi)容,應(yīng)該使用正則表達(dá)式,并加添加g標(biāo)志。返回被替換后的字符串,不改變?cè)址?/li>
var str = "abcabcdabdabe";
str.replace("abc", "abcd"); //"abcdabcdabdabe"
str.replace(/abc/g, "a");
  1. 如果第二個(gè)參數(shù)是字符串
    此時(shí),不僅可以使用普通字符串來(lái)替換第一個(gè)參數(shù)匹配到的內(nèi)容,也可以使用一些特殊的字符序列,將正則表達(dá)式得到的值插入到結(jié)果字符串中。
字符序列 替換文本
$$ $
$& RegExp.lastMatch
$' RegExp.leftContext
$` RegExp.rightContext
$n 第n個(gè)捕獲組的字符串
$nn 第nn個(gè)捕獲組的字符串

舉一些例子:

var str = "cat, bat, sat, fat";
result = str.replace(/(.at)/g, "word ($1)")
"word (cat), word (bat), word (sat), word (fat)"
result = str.replace(/(.at)/g, "word ($')")
"word (, bat, sat, fat), word (, sat, fat), word (, fat), word ()"
result = str.replace(/(.at)/g, "word ($`)")
"word (), word (cat, ), word (cat, bat, ), word (cat, bat, sat, )"
result = str.replace(/(.at)/g, "word ($$)")
"word ($), word ($), word ($), word ($)"
result = str.replace(/(.at)/g, "word ($&)")
"word (cat), word (bat), word (sat), word (fat)"
result = str.replace(/(b)(at)/g, "word ($2)")
"cat, word (at), sat, fat"
  1. replace() 方法的第二個(gè)參數(shù)可以是函數(shù)。在這種情況下,每個(gè)匹配都調(diào)用該函數(shù),它返回的字符串將作為替換文本使用。該函數(shù)的第一個(gè)參數(shù)是匹配模式的字符串。接下來(lái)的參數(shù)是與模式中的子表達(dá)式匹配的字符串,可以有 0 個(gè)或多個(gè)這樣的參數(shù)。接下來(lái)的參數(shù)是一個(gè)整數(shù),聲明了匹配在原字符串中出現(xiàn)的位置。最后一個(gè)參數(shù)是原字符串本身。
    書中提到了一個(gè)例子:
function htmlEscape(text){
  return text.replace(/[<>"&]/g,         
    function(match, pos, originalText){
      switch(match){
        case "<":
          return "&lt;";
        case ">":
          return "&gt;";
        case "&":
          return "&amp;";
        case "\"":
          return "&quot;";
      }
  });
}
alert(htmlEscape("<p class=\"greeting\">Hello world!</p>"));
//&lt;p class=&quot;greeting&quot;&gt;Hello world!&lt;/p&gt;

W3C中還有一個(gè)例子,可以將所有單詞的首字母轉(zhuǎn)化為大寫:

name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
  return word.substring(0,1).toUpperCase()+word.substring(1);}
);

通過(guò)第三個(gè)參數(shù),我們可以使用不同的轉(zhuǎn)義序列分別替代< > & \

  • split()
    將一個(gè)字符串基于指定分隔符分割成多個(gè)子字符串,返回子字符串構(gòu)成的數(shù)組,第一個(gè)參數(shù)作為分隔符,可以是字符串,也可以是正則表達(dá)式,第二個(gè)參數(shù)可選,指定數(shù)組大小。
var str = "Hat, Bat, Rat, Cat";
str.split();
//["Hat, Bat, Rat, Cat"]
str.split(",");
//(4) ["Hat", " Bat", " Rat", " Cat"]
str.split(",", 2);
//(2) ["Hat", " Bat"]
str.split(/at/);
//(5) ["H", ", B", ", R", ", C", ""]
字符串比較方法

localeCompare()用于比較兩個(gè)字符串:
strA.localeCompare(strB)
如果strA < strB,返回一個(gè)負(fù)數(shù)(不一定是-1);
如果strA > strB,返回一個(gè)正數(shù)(不一定是1);
如果strA == strB,返回0。
localeCompare()的比較方法因地區(qū)而異。

fromCharCode()

String構(gòu)造函數(shù)中的靜態(tài)方法,接受一個(gè)或多個(gè)字符編碼,將它們轉(zhuǎn)換成字符串。

String.fromCharCode(33, 23, 3); //!??
HTML方法

下面的例子列舉了可以生成標(biāo)準(zhǔn)HTML標(biāo)簽的方法:

var str = "Hello World!"
str.anchor("welcome"); //<a name="welcome">Hello World!</a>
str.big(); //<big>Hello World!</big>
str.bold(); //<b>Hello World!</b>
str.fixed(); //<tt>Hello World!</tt>
str.fontcolor("red"); //<font color="red">Hello World!</font>
str.fontsize(12); //<font size="12">Hello World!</font>
str.italics(); //<i>Hello World!</i>
str.link("www.itdecent.cn"); //<a href="www.itdecent.cn">Hello World!</a>
str.small(); //<small>Hello World!</small>
str.strike(); //<strike>Hello World!</strike>
str.sub(); //<sub>Hello World!</sub>
str.sup(); //<sup>Hello World!</sup>

內(nèi)置對(duì)象

Global

所有全局作用域的屬性和函數(shù)都是Global對(duì)象的屬性

encodeURI()encodeURIComponent()

這兩個(gè)編碼方法可以使用UTF-8對(duì)URI進(jìn)行編碼,當(dāng)我們的URI中包含某些無(wú)效字符時(shí),可以使用這兩個(gè)方法將URI轉(zhuǎn)換成瀏覽器可以識(shí)別的字符串。

  • encodeURI()
  1. 編碼范圍
    ASCII字母、數(shù)字、~!@#$&*()=:/,;?+'之外的字符。
  2. 例子
encodeURI("http://www.baidu.com/some other thing");
"http://www.baidu.com/some%20other%20thing"

可以看出,encodeURI()將空格轉(zhuǎn)化為%20,返回一個(gè)可以直接被瀏覽器識(shí)別的URI。

  • encodeURIComponent()
  1. 編碼范圍
    ASCII字母、數(shù)字、~!*()'之外的字符。
  2. 例子
encodeURIComponent("http://www.baidu.com/some other thing");
"http%3A%2F%2Fwww.baidu.com%2Fsome%20other%20thing"

可以看出encodeURIComponent()將空格、:、 /都進(jìn)行了編碼,然而返回的結(jié)果似乎是一個(gè)不可用的URI,那么這個(gè)方法有什么用呢?
假如說(shuō)我們要訪問(wèn)如下URI:

https://www.baidu.com/s?://

如果不進(jìn)行編碼,瀏覽器會(huì)將所有的反斜杠都視為分隔符,這顯然不是我們的初衷。這種情況下,我們應(yīng)對(duì)://進(jìn)行編碼。

var baseURI = "https://www.baidu.com/s?wd=";
var s = encodeURIComponent("://");
var uri = baseURI + s;
console.log(uri); //https://www.baidu.com/s?wd=%3A%2F%2F
decodeURI()decodeURIComponent()

有編碼自然就有解碼,decodeURI()只能解碼encodeURI()處理過(guò)的字符串,而decodeURIComponent()則可以解碼任何特殊字符的編碼。
還是上述的例子:

decodeURI(uri)
"https://www.baidu.com/s?wd=%3A%2F%2F"
decodeURIComponent(uri)
"https://www.baidu.com/s?wd=://"
eval

只接受一個(gè)參數(shù),可執(zhí)行的Javascript字符串。解析器遇到eval()時(shí),會(huì)將參數(shù)當(dāng)作實(shí)際的ECMAScript語(yǔ)句來(lái)解析,并且eval()中的代碼被納入調(diào)用eval()的執(zhí)行環(huán)境中。

var message = "hello";
eval("message += ' world!'; function say(){ console.log(message);}")
say();
hello world!

書中提到在eval()中創(chuàng)建的變量和函數(shù)不會(huì)被提升。但筆者試了一下,發(fā)現(xiàn)不是這樣:

eval("var tt='aa'; function test(){console.log(tt); var tt='dd'; console.log(tt);} test();")
// undefined dd
eval("test(); function test(){var tt='dd'; console.log(tt);}")
// dd
test();
eval("function test(){var tt='dd'; console.log(tt);}")
//undefined

嚴(yán)格模式下,外部訪問(wèn)不到eval()中創(chuàng)建的函數(shù)和變量,也不可以為eval賦值。

Global對(duì)象的其他函數(shù)

isNaN()、isFinite()、parseInt()以及parseFloat()等。

Global對(duì)象的屬性

  • undefined NaN Infinity
  • 構(gòu)造函數(shù)
    Object Array Function Boolean String Number Date RegExp Error EvalError RangeError ReferenceError SyntaxError TypeError URIError
window

Web瀏覽器中,Global對(duì)象中的變量和函數(shù)都是window對(duì)象的屬性

Math

Math對(duì)象的屬性
屬性 說(shuō)明
Math.E e
Math.LN10 10的自然對(duì)數(shù)
Math.LN2 2的自然對(duì)數(shù)
Math.LOG2E 以2為底的e的對(duì)數(shù)
Math.LOG10E 以10為底的e的對(duì)數(shù)
Math.PI π
Math.SQRT1_2 1/2的平方根
Math.SQRT2 2的平方根
min()max()

接受多個(gè)數(shù)值參數(shù),得到其中的最大、最小值。
如果我們要從一個(gè)數(shù)值數(shù)組中獲得最大最小值呢?可以使用apply:

var array = [4, 5, 7, 1, 3, 10, 6];
Math.max.apply(Math, array)
//10

需要注意的是,要將Math作為max()this。

舍入方法
  • Math.ceil():向上舍入
  • Math.round():四舍五入
  • Math.floor():向下舍入
var num1 = 24.5, num2 = 24.4;
Math.ceil(num1); // 25
Math.floor(num1); // 24
Math.round(num1); // 25
Math.round(num2); // 24
random

返回一個(gè)大于等于0小于1的隨機(jī)數(shù)。書中提到了一個(gè)從某個(gè)整數(shù)范圍內(nèi)隨機(jī)選擇一個(gè)值的方法:

value = Math.floor(Math.random() * range + minValue)

比如返回一個(gè)1到10中的一個(gè)隨機(jī)整數(shù):

var num = Math.floor(Math.random() * 10 + 1)
其他方法
方法 說(shuō)明
Math.abs(num) 返回num的絕對(duì)值
Math.exp(num) 返回Math.Enum次冪
Math.log(num) 返回num的自然對(duì)數(shù)
Math.pow(num, power) 返回numpower次冪
Math.sqrt(num) 返回num的平方根
Math.acos(x) 返回x的反余弦值
Math.asin(x) 返回x的反正弦值
Math.atan(x) 返回x的反正切值
Math.atan2(y, x) 返回y/x的反正切值
Math.cos(x) 返回x的余弦值
Math.sin(x) 返回x的正弦值
Math.tan(x) 返回x的正切值
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容