1. 程式人生 > >javascript中陣列和字串的方法比較

javascript中陣列和字串的方法比較

前面的話

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

可索引

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

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

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

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

console.log(arr[false]);//undefined
console.log(arr[-1]);//undefined
console.log(arr[NaN]);//undefined console.log(arr[]);//報錯

轉換

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

【split()】

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

  該方法可以接受(可選的)第二個引數用於指定陣列的大小。如果第二個引數為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()方法返回的結果中以空字串表示

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'));//9
console.log(string.indexOf('ld',undefined));//9
console.log(string.indexOf('ld',NaN));//9
console.log(string.indexOf('ld',-1));//9
console.log(string.indexOf('ld',10));//15
console.log(string.indexOf('ld',[10]));//15
console.log(string.indexOf('true',[10]));//-1
console.log(string.indexOf(false,[10]));//-1
var arr = ['a','b','c','d','e','a','b'];
console.log(arr.indexOf('a',undefined));//0
console.log(arr.indexOf('a',NaN));//0
console.log(arr.indexOf('a',1));//5
console.log(arr.indexOf('a',true));//5
console.log(arr.indexOf('a',-1));//max(0,-1+7)=6; -1
console.log(arr.indexOf('a',-5));//max(0,-5+7)=2; 5
console.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'));//15
console.log(string.lastIndexOf('ld',undefined));//15
console.log(string.lastIndexOf('ld',NaN));//15
console.log(string.lastIndexOf('ld',-1));//-1
console.log(string.lastIndexOf('h',-1));//0
console.log(string.lastIndexOf('w',undefined));//12

console.log(string.lastIndexOf('ld',10));//9
console.log(string.lastIndexOf('ld',[10]));//9
console.log(string.lastIndexOf('true',[10]));//-1
console.log(string.lastIndexOf(false,[10]));//-1
var arr = [1,2,3,'1','2','3'];
console.log(arr.lastIndexOf('2'));//4
console.log(arr.lastIndexOf(3));//2
console.log(arr.lastIndexOf(0));//-1

var arr = ['a','b','c','d','e','a','b'];
console.log(arr.lastIndexOf('b'));//6
console.log(arr.lastIndexOf('b',undefined));//-1
console.log(arr.lastIndexOf('a',undefined));//0
console.log(arr.lastIndexOf('b',NaN));//-1
console.log(arr.lastIndexOf('b',1));//1
console.log(arr.lastIndexOf('b',-1));//max(0,-1+7)=6; 6
console.log(arr.lastIndexOf('b',-5));//max(0,-5+7)=2; 1
console.log(arr.lastIndexOf('b',-50));//max(0,-50+7)=0; -1

順序

【反轉】

  在陣列Array中存在reverse()方法來反轉陣列

var array = [1,2,4,3,5];
console.log(array,array.reverse());//[5,3,4,2,1] [5,3,4,2,1]

  而字串String也可以利用call()或apply()來實現反轉

var str = '12435';
console.log(str,Array.prototype.reverse.apply(str.split('')).join(''));//'12435' '53421'

【排序】

  在陣列Array中存在sort()方法來對陣列排序,預設按字串升序排列陣列項

var array = [1,2,4,3,5];
console.log(array,array.sort());//[1,2,3,4,5] [1,2,3,4,5]

  而字串String也可以利用call()或apply()來實現排序

var str = '12435';
console.log(str,Array.prototype.sort.apply(str.split('')).join(''));//'12435' '12345'