/**
* 本文純粹是梳理一下目前W3C標准中Array對象的自帶Method。
* 全文沒啥營養,不過最后性能測試的部分,倒是拋出了一些疑問。
*/
賦值方法 (Mutator methods)
這些方法直接修改數組自身
pop 和 push
Array
.pop(); // 刪除數組最后一個元素,返回被刪除的元素
Array
.push(element1, ..., elementN); // 在數組尾部插入1-N個元素,返回操作后數組的length
通過這 pop 和 push ,就能把數組模擬成 堆棧(stack) 來進行操作。
堆棧這種數據結構的特點,就是“后進先出”(LIFO, Last In First Out)。
shift 和 unshift
Array
.shift(); //
刪除數組第一個元素,返回被刪除的元素
Array
.unshift(element1, ..., elementN) ;
// 在數組頭部插入1-N個元素,返回操作后數組的length
利用 shift 和 unshift 則可以實現 隊列(
queue) 的操作。
隊列的操作方式和堆棧相反,采用“先進先出”(FIFO, First-In-First-Out)。
splice
Array
.splice(index , howMany[, element1[, ...[, elementN]]]);
Array
.splice(index);
參數:
index:規定從何處添加/刪除元素。
howmany:規定應該刪除多少元素。
elements:規定要添加到數組的新元素,從 index 所指的下標處開始插入。
splice方法是對 pop、push、shift、unshift 的一個補充。
返回值是被刪除的元素。
reverse
Array
.reverse(); // 顛倒數組中元素的順序,並返回逆序后的數組
sort
Array
.sort([compareFunction]);
如果調用該方法時沒有使用參數,將按字母順序對數組中的元素進行排序。
說得更精確點,是按照字符編碼的順序進行排序。
如果想按照其他標准進行排序,就需要提供比較函數,該函數要比較兩個值,然后返回一個用於說明這兩個值的相對順序的數字。比較函數應該具有兩個參數 a 和 b,其返回值如下:
- 若 a 小於 b,在排序后的數組中 a 應該出現在 b 之前,則返回一個小於 0 的值。
- 若 a 等於 b,則返回 0。
- 若 a 大於 b,則返回一個大於 0 的值。
訪問方法(Accessor methods)
這些方法只是返回相應的結果,而不會修改數組本身
concat
Array.concat(value1, value2, ..., valueN); // 鏈接2個或多個數組,並返回合並后的數組
但有一個需要注意的地方,用下面的例子說明:
1 var arr = [1, 2, 3]; 2 arr.concat(4, 5); // return [1, 2, 3, 4, 5] 3 arr.concat([4, 5]); // return [1, 2, 3, 4, 5] 4 arr.concat([4, 5], [6, 7]); // return [1, 2, 3, 4, 5, 6, 7] 5 arr.concat(4, [5, [6, 7]]); // return [1, 2, 3, 4, 5, [6, 7]]
join
string = Array.join(separator);
把數組中的所有元素放入一個字符串。其中,元素之間是通過指定的分隔符進行分隔的。
默認的分隔符是逗號(,),返回值是合並后字符串。
1 [1, 2, 3].join(); // return "1,2,3"
Array.join()方法,實際上是String.splite()的逆向操作。
slice
Array.slice(begin[, end]); // 數組中返回選定的元素
toString
Array.toString(); // 這個就不說了,所有JavaScript都有toString這個方法
indexOf 和 lastIndexOf *
[ECMAScript 5]
Array.indexOf(searchElement[, fromIndex]); // 從頭開始搜索
Array.lastIndexOf(searchElement[, fromIndex]); // 從尾開始搜索
searchElement:需要搜索的值
fromIndex:索引,指示搜索從哪里開始
迭代方法(Iteration methods)
forEach
*
[ECMAScript 5]
Array.forEach(callback[, thisArg]); // 從頭到尾遍歷一次數組,並為數組中的每個元素,調用指定的函數
參數:
callback:遍歷數組時調用的函數
thisArg:指定 callback 的作用域
另外,callback會調用三個參數:
value:數組元素
index:數組索引
array:數組本身
1 [1, 2].forEach(function(value, index, array) { 2 console.log(value, index, array); 3 }); 4 // return 5 // 1 0 [1, 2] 6 // 2 1 [1, 2]
Note:forEach是無法通過break來中斷數組的遍歷。
解決方法:利用try方法來拋出異常,終止遍歷。
1 try { 2 [1,2,3].forEach(function(val) { 3 console.log(val); 4 throw(e) 5 }); 6 } catch(e) { 7 console.log(e); 8 }
map
*
[ECMAScript 5]
Array.map(callback[, thisArg]); // 遍歷數組元素,調用指定函數,並以數組返回所有結果
參數:
callback:遍歷數組時調用的函數
thisObject :指定 callback 的作用域
例子:
1 [1, 2, 3].map(function(num) { // return [2, 3, 4] 2 return num + 1; 3 });
filter
*
[ECMAScript 5]
Array.filter(callback[, thisObject]); // 遍歷數組調用方法,滿足條件(返回true)的元素,將被添加到返回值的數組中
參數:
callback:遍歷數組時調用的函數
thisObject :指定 callback 的作用域
例子:
1 [1, 2, 3].filter(function(num) { // return [1] 2 return num < 2; 3 });
every 和 some
*
[ECMAScript 5]
Array.every(callback[, thisObject]); // “與”
Array.some(callback[, thisObject]); // “或”
參數:
callback:遍歷數組時調用的函數
thisObject:指定 callback 的作用域
every:當所有元素調用函數都返回true,結果才返回true,不然均返回false。
some:當所有元素調用函數都返回false,結果才返回false,不然均返回true。
一旦every和some的返回值確定,就會立刻停止遍歷。
例子:
1 [1, 2, 3]. every(function(num) { // return false 2 return num > 1; 3 }); 4 [1, 2, 3]. some(function(num) { // return true 5 return num > 2; 6 });
reduce 和 reduceRight
*
[ECMAScript 5]
Array.reduce(callback[, initialValue]); // 使用指定的方法將數組元素進行組合,按索引從低到高(從左到右)
Array.reduceRight(callback[, initialValue]); // 使用指定的方法將數組元素進行組合,按索引從高到低(從右到左)
參數:
callback:遍歷數組時調用的函數
initialValue:第一個次調用callback時傳入的previousValue
另外,callback會調用四個參數:
previousValue:到目前為止的操作累積結果
currentValue:數組元素
index:數組索引
array:數組本身
例子:
1 [1, 2, 3]. reduce(function(x, y) { // return 106 2 return x + y; 3 }, 100);
性能測試
測試系統:Windows 7
測試瀏覽器:Chrome 26.0.1386.0
1 var arr = []; 2 3 for(var i = 0; i < 999999; i++) { 4 arr.push(i); 5 }
forEach
1 function forEachTest() { 2 howTime("forEach", function() { 3 var num = 0; 4 arr.forEach(function(val, key) { 5 num += val; 6 }); 7 }); 8 9 howTime("for", function() { 10 var num = 0; 11 for(var i = 0, len = arr.length; i < len; i++) { 12 num += arr[i]; 13 } 14 }); 15 }
下面是隨機進行的3次測試結果(具體結果與電腦配置有關,結果越小則性能越好):
time_forEach | time_for |
1421.000ms | 64.000ms |
1641.000ms | 63.000ms |
1525.000ms | 63.000ms |
可以看到,Chrome並沒有對forEach做專門的優化,和直接用for循環遍歷相比,性能還是有很大的差距。
因為forEach是 ECMAScript 5 的東西,舊版瀏覽器並不支持。
不過MDN都有給出向下兼容的解決方法:
1 if(!Array.prototype.forEach) { 2 Array.prototype.forEach = function(fn, scope) { 3 for(var i = 0, len = this.length; i < len; ++i) { 4 fn.call(scope, this[i], i, this); 5 } 6 } 7 }
離譜的是,原生的 forEach 方法,在性能上,居然比不上自己構造的 forEach!
還有,Array對象其他的迭代方法呢?
大家看看這個Demo就基本清楚了:http://maplejan.sinaapp.com/demo/ArratMethod.html
另外,還發現了一個有意思的情況。
如果直接在控制台運行Demo的JavaScript代碼,你會發現性能上有很大差異!
這個時候,直接用for循環寫的方法,性能會更差。
對於這個疑問,在知乎上提問了,問題地址:http://www.zhihu.com/question/20837774
作者:Maple Jan