javascript中數組和字串的方法對比,javascript數組

來源:互聯網
上載者:User

javascript中數組和字串的方法對比,javascript數組

前面的話

字串和數組有很多的相同之處,它們的方法眾多,且相似性很高;但它們又有不同之處,字串是不可變值,於是可以把其看作唯讀數組。本文將對字串和數組的類似方法進行比較

可索引

ECMAScript5定義了一種訪問字元的方法,使用方括弧加數字索引來訪問字串中的特定字元

可索引的字串的最大的好處就是簡單,用方括弧代替了charAt()調用,這樣更加簡潔、可讀並且可能更高效。不僅如此,字串的行為類似於數組的事實使得通用的數組方法可以應用到字串上

如果參數超出範圍或是NaN時,則輸出undefined

var str = "hello";console.log(str[0]);//hconsole.log(str[[1]]);//econsole.log(str[false]);//undefinedconsole.log(str[-1]);//undefinedconsole.log(str[NaN]);//undefinedconsole.log(str[]);//報錯
var arr = ['h','e','l','l','o'];console.log(arr[0]);//hconsole.log(arr[[1]]);//econsole.log(arr[false]);//undefinedconsole.log(arr[-1]);//undefinedconsole.log(arr[NaN]);//undefinedconsole.log(arr[]);//報錯

轉換

字串可以使用split()方法轉換為數組;而數組可以使用join()方法轉換為字串

【split()】

split()方法基於指定的分隔字元將一個字串分割成多個字串,並將結果放在一個數組中,分隔字元可以是字串,也可以是一個Regex

該方法可以接受(可選的)第二個參數用於指定數組的大小。如果第二個參數為0-array.length範圍內的值時,按照指定參數輸出,其他情況將所有結果都輸出

若指定分隔字元沒有出現在字串中,則以數組的形式返回原字串的值

var colorText = 'red,blue,green,yellow';console.log(colorText.split(''));//["r", "e", "d", ",", "b", "l", "u", "e", ",", "g", "r", "e", "e", "n", ",", "y", "e", "l", "l", "o", "w"]console.log(colorText.split(','));//["red", "blue", "green", "yellow"]console.log(colorText.split(',',2));//["red", "blue"]console.log(colorText.split(',',6));//["red", "blue", "green", "yellow"]console.log(colorText.split('-'));//["red,blue,green,yellow"]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-會識別為[",",",",","]

【join()】

join()方法可以使用不同的分隔字元來構建這個字串,join()方法只接收一個參數,用作分隔字元的字串,然後返回包含所有數組項的字串

如果不給join()方法傳入任何值,則使用逗號作為分隔字元

var a = [1,2,3];console.log(a.join());//'1,2,3'console.log(a.join(' '));//'1 2 3'console.log(a.join(''));//'123'var b = new Array(10);b.join('-');//'---------',9個連字號組成的字串

如果數組中的某一項的值是null或者undefined,則該值在join()方法返回的結果中以Null 字元串表示

var colors = [1,undefined,2,null,3];console.log(colors.join());//'1,,2,,3'

由於字串是類數組對象,所以,也可以使用join()方法

console.log(Array.prototype.join.call('hello', '-'));// "h-e-l-l-o"
var str = 'test';var arr = str.split('')//["t", "e", "s", "t"]console.log(arr.join('-'));//'t-e-s-t'

拼接  

字串和數組共同擁有拼接方法concat()

var value = 'hello';console.log(value.concat('world'));//'helloworld'console.log(value.concat(['world']));//'helloworld'console.log(value.concat([['world']]));//'helloworld'
var value = ['hello'];console.log(value.concat('world'));//["hello", "world"]console.log(value.concat(['world']));//["hello", "world"]console.log(value.concat([['world']]));//["hello", ["world"]]

建立

字串和數組都擁有建立方法slice(),分別用於建立子字串和子數組

slice()方法基於當前數組(或字串)中的一個或多個項建立一個新數組(或字串),接受一個或兩個參數,即要返回項的起始和結束位置,最後返回新數組(或字串)

slice(start,end)方法需要兩個參數start和end,返回這個數組(或字串)中從start位置到(但不包含)end位置的一個子數組(或字串);如果end為undefined或不存在,則返回從start位置到數組(或字串)結尾的所有項

如果start是負數,則start = max(length + start,0)

如果end是負數,則end = max(length + end,0)

start和end無法交換位置

var numbers = [1,2,3,4,5];console.log(numbers.slice(2));//[3,4,5]console.log(numbers.slice(2,undefined));//[3,4,5]console.log(numbers.slice(2,3));//[3]console.log(numbers.slice(2,1));//[]console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]console.log(numbers.slice(-8));//max(5 + -8,0)=0 -> [1,2,3,4,5]console.log(numbers.slice(0,-3));//-3+5=2 -> [1,2]console.log(numbers.slice(-2,-1));//-2+5=3;-1+5=4; -> [4]
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,undefined));//'llo world'console.log(stringValue.slice(2,-5));//'llo 'console.log(stringValue.slice(2,-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'

位置

字串和數組都擁有尋找位置的兩個方法:indexOf()和lastIndexOf()。位置方法和中括弧[]讀取方法正好相反,一個是通過項尋找索引,一個是通過索引尋找項

【indexOf()】

indexOf(search,start)方法接收search和start兩個參數,返回search首次出現的位置,如果沒有找到則返回-1

字串中的search參數會調用String()轉型函數,將該參數的非字串值轉換為字串;而數組中的search參數則使用嚴格相等運算子(===)進行比較

不論是數組還是字串,第二個參數start都會隱式調用Number()轉型函數,將start非數字值(undefined除外)轉換為數值;若忽略該參數或該參數為undefined、NaN時,start = 0

若start參數為負數,字串的處理是將start=0;而數組的處理是start = max(0,start+length)

var string = 'hello world world';console.log(string.indexOf('ld'));//9console.log(string.indexOf('ld',undefined));//9console.log(string.indexOf('ld',NaN));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',10));//15console.log(string.indexOf('ld',[10]));//15console.log(string.indexOf('true',[10]));//-1console.log(string.indexOf(false,[10]));//-1
var arr = ['a','b','c','d','e','a','b'];console.log(arr.indexOf('a',undefined));//0console.log(arr.indexOf('a',NaN));//0console.log(arr.indexOf('a',1));//5console.log(arr.indexOf('a',true));//5console.log(arr.indexOf('a',-1));//max(0,-1+7)=6; -1console.log(arr.indexOf('a',-5));//max(0,-5+7)=2; 5console.log(arr.indexOf('a',-50));//max(0,-50+7)=0; 0

【lastIndexOf()】

與indexOf()方法相反,lastIndexOf()方法是從右向左尋找

lastIndexOf(search,start)方法接收search和start兩個參數,返回searchString第一次出現的位置,如果沒有找到則返回-1

類似地,字串中的search參數會調用String()轉型函數,將該參數的非字串值轉換為字串;而數組中的search參數則使用嚴格相等運算子(===)進行比較

不論是數組還是字串,第二個參數start都會隱式調用Number()轉型函數,將start非數字值(undefined除外)轉換為數值

若忽略該參數或該參數為undefined、NaN時,字串的處理是start = length - 1;而數組的處理是start = 0

若start參數為負數,字串的處理是將start=0;而數組的處理是start = max(0,start+length)

var string = 'hello world world';console.log(string.lastIndexOf('ld'));//15console.log(string.lastIndexOf('ld',undefined));//15console.log(string.lastIndexOf('ld',NaN));//15console.log(string.lastIndexOf('ld',-1));//-1console.log(string.lastIndexOf('h',-1));//0console.log(string.lastIndexOf('w',undefined));//12console.log(string.lastIndexOf('ld',10));//9console.log(string.lastIndexOf('ld',[10]));//9console.log(string.lastIndexOf('true',[10]));//-1console.log(string.lastIndexOf(false,[10]));//-1
var arr = [1,2,3,'1','2','3'];console.log(arr.lastIndexOf('2'));//4console.log(arr.lastIndexOf(3));//2console.log(arr.lastIndexOf(0));//-1var arr = ['a','b','c','d','e','a','b'];console.log(arr.lastIndexOf('b'));//6console.log(arr.lastIndexOf('b',undefined));//-1console.log(arr.lastIndexOf('a',undefined));//0console.log(arr.lastIndexOf('b',NaN));//-1console.log(arr.lastIndexOf('b',1));//1console.log(arr.lastIndexOf('b',-1));//max(0,-1+7)=6; 6console.log(arr.lastIndexOf('b',-5));//max(0,-5+7)=2; 1console.log(arr.lastIndexOf('b',-50));//max(0,-50+7)=0; -1

以上這篇javascript中數組和字串的方法對比就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.