標籤:item span copy man last 一個 index pre 注意
常用方法1. array.concat(array1, array2,...arrayN);
合并多個數組,返回合并後的新數組,原數組沒有變化。
const array = [1,2].concat([‘a‘, ‘b‘], [‘name‘]);// [1, 2, "a", "b", "name"]
2. array.every(callback[, thisArg]);
檢測數組中的每一個元素是否都通過了callback測試,全部通過返回true,否則返回false。
// callback定義如下: element:當前元素值;index:當前元素下標; array:當前數組function callback(element, index, array) { // callback函數必須返回true或者false告知every是否通過測試 return true || false;}3. array.filter(callback[, thisArg]);
返回一個新數組,包含通過callback函數測試的所有元素。
// callback定義如下,三個參數: element:當前元素值;index:當前元素下標; array:當前數組function callback(element, index, array) { // callback函數必須返回true或者false,返回true保留該元素,false則不保留。 return true || false;}const filtered = [1, 2, 3].filter(element => element > 1);// filtered: [2, 3]; 4. array.find(callback[, thisArg]);
返回通過callback函數測試的第一個元素,否則返回undefined,callback函數定義同上。
const finded = [1, 2, 3].find(element => element > 1);// finded: 2
如果你需要找到一個元素的位置或者一個元素是否存在於數組中,使用Array.prototype.indexOf() 或 Array.prototype.includes()。
5. array.findIndex(callback[, thisArg]);
返回通過callback函數測試的第一個元素的索引,否則返回-1,callback函數定義同上。
const findIndex = [1, 2, 3].findIndex(element => element > 1);// findIndex: 1
6. array.includes(searchElement, fromIndex);
includes() 方法用來判斷一個數組是否包含一個指定的值,返回 true或 false。searchElement:要尋找的元素;fromIndex:開始尋找的索引位置。
[1, 2, 3].includes(2, 2);// false
7. array.indexOf(searchElement[, fromIndex = 0]);
返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。searchElement:要尋找的元素;fromIndex:開始尋找的索引位置。
[2, 9, 7, 8, 9].indexOf(9);// 1
array.lastIndexOf(searchElement[, fromIndex = arr.length - 1])
返回指定元素在數組中的最後一個的索引,如果不存在則返回-1, 從數組的後面向前尋找同上
8. array.join(separator=‘,‘);
將數組中的元素通過separator串連成字串,並返回該字串,separator預設為","。
[1, 2, 3].join(‘;‘);// "1;2;3"
9. array.map(callback[, thisArg]);
返回一個新數組,新數組中的每個元素都是調用callback函數後返回的結果。注意:如果沒有return值,則新數組會插入一個undefined值。
array.map由於不具有過濾的功能,因此array調用map函數時,如果array中的資料並不是每一個都會return,則必須先filter,然後再map,即map調用時必須是對數組中的每一個元素都有效。
const maped = [{name: ‘aa‘, age: 18}, {name: ‘bb‘, age: 20}].map(item => item.name + ‘c‘);// maped: [‘aac‘, ‘bbc‘];10. array.pop() 與 array.shift();
pop為從數組中刪除最後一個元素,並返回最後一個元素的值,原數組的最後一個元素被刪除。數組為空白時返回undefined。
[1, 2, 3].pop();// 3
shift刪除數組的第一個元素,並返回第一個元素,原數組的第一個元素被刪除。數組為空白返回undefined。
const shifted = [‘one‘, ‘two‘, ‘three‘].shift();// shifted: ‘one‘
11. array.push(element1, element2, ....elementN) 與 array.unshift(element1, element2, ...elementN);
push是將一個或多個元素添加到數組的末尾,並返回新數組的長度; unshift將一個或多個元素添加到數組的開頭,並返回新數組的長度。唯一的區別就是插入的位置不同。
const arr = [1, 2, 3];const length = arr.push(4, 5);// arr: [1, 2, 3, 4, 5]; length: 5
push和unshift方法具有通用性,通過call()或者apply()方法調用可以完成合併兩個數組的操作。
const vegetables = [‘parsnip‘, ‘potato‘];const moreVegs = [‘celery‘, ‘beetroot‘]; // 將第二個數組融合進第一個數組// 相當於 vegetables.push(‘celery‘, ‘beetroot‘);Array.prototype.push.apply(vegetables, moreVegs);或者[].push.apply(vegetables, moreVegs);// vegetables: [‘parsnip‘, ‘potato‘, ‘celery‘, ‘beetroot‘]
12. array.reduce(callback[, initialValue]);
對數組中的每個元素(從左至右)執行callback函數累加,將其減少為單個值。
const total = [0, 1, 2, 3].reduce((sum, value) => { return sum + value;}, 0);// total is 6 const flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => { return a.concat(b);}, []);// flattened is [0, 1, 2, 3, 4, 5] // initialValue累加器初始值, callback函數定義:function callback(accumulator, currentValue, currentIndex, array) {}accumulator代表累加器的值,初始化時,如果initialValue有值,則accumulator初始化的值為initialValue,整個迴圈從第一個元素開始;initialValue無值,則accumulator初始化的值為數組第一個元素的值,currentValue為數組第二個元素的值,整個迴圈從第二個元素開始。initialValue的資料類型可以是任意類型,不需要跟原數組內的元素實值型別一致。 const newArray = [{ name: ‘aa‘, age: 1 }, { name: ‘bb‘, age: 2 }, { name: ‘cc‘, age: 3 }].reduce((arr, element) => { if (element.age >= 2) { arr.push(element.name); } return arr; // 必須有return,因為return的傳回值會被賦給新的累加器,否則累加器的值會為undefined。}, []); // newArray is ["bb", "cc"]; 上面代碼的同等寫法:const newArray = [{ name: ‘aa‘, age: 1 }, { name: ‘bb‘, age: 2 }, { name: ‘cc‘, age: 3 }].filter(element => element.age >= 2).map(item => item.name);// newArray is ["bb", "cc"]; 對於reduce的特殊用法,其實類似於省略了一個變數初始化步驟,然後通過每次的callback的返回修改該變數,最後返回最終變數值的過程,類似於一個變數聲明 + 一個forEach執行過程。const newArray = [];[{ name: ‘aa‘, age: 1 }, { name: ‘bb‘, age: 2 }, { name: ‘cc‘, age: 3 }].forEach(item => { if (item.age >=2) { newArray.push(item.name); }});array.reduceRight()
使用同上,與reduce()的執行方向相反
13. array.reverse();
將數組中元素的位置顛倒。
[‘one‘, ‘two‘, ‘three‘].reverse();// [‘three‘, ‘two‘, ‘one‘],原數組被翻轉
14. array.slice(begin, end)
返回一個新數組,包含原數組從begin 到 end(不包含end)索引位置的所有元素。
const newArray = [‘zero‘, ‘one‘, ‘two‘, ‘three‘].slice(1, 3);// newArray: [‘one‘, ‘two‘];
15. array.some(callback[, thisArg]);
判斷數組中是否包含可以通過callback測試的元素,與every不同的是,這裡只要某一個元素通過測試,即返回true。callback定義同上。
[2, 5, 8, 1, 4].some(item => item > 6);// true
16. array.sort([compareFunction]);
對數組中的元素進行排序,compareFunction不存在時,元素按照轉換為的字串的諸個字元的Unicode位點進行排序,慎用!請使用時一定要加compareFunction函數,而且該排序是不穩定的。
[1, 8, 5].sort((a, b) => { return a-b; // 從小到大排序});// [1, 5, 8]17. array.splice(start[, deleteCount, item1, item2, ...]);
通過刪除現有元素和/或添加新元素來更改一個數組的內容。start:指定修改的開始位置;deleteCount:從 start位置開始要刪除的元素個數;item...:要添加進數組的元素,從start 位置開始。
傳回值是由被刪除的元素組成的一個數組。如果只刪除了一個元素,則返回只包含一個元素的數組。如果沒有刪除元素,則返回空數組。
如果 deleteCount 大於start 之後的元素的總數,則從 start 後面的元素都將被刪除(含第 start 位)。
const myFish = [‘angel‘, ‘clown‘, ‘mandarin‘, ‘sturgeon‘]; const deleted = myFish.splice(2, 0, ‘drum‘); // 在索引為2的位置插入‘drum‘// myFish 變為 ["angel", "clown", "drum", "mandarin", "sturgeon"],deleted為[]
18.其他
array.copyWithin(target, start [, end = this.length])【有相容性問題】
用於在數組內的替換操作,即替換元素和被替換元素都是數組內的元素
參數皆為整數,允許start,end為負數(倒數第n個)
array.fill(value [,statrt = 0[, end = this.length]])
將數組中指定區間的所有元素的值,都替換成value
start,end允許為負值,同上
array.toString()
返回一個字串,該字串由數組中的每個元素的toString()傳回值經調用join()方法串連(由逗號隔開)組成。
var arr = [‘abc‘, 2, {a: ‘test‘}] console.log(arr.toString()) //‘abc,2,[object Object]‘
array.toLocaleString()
返回一個字串表示數組中的元素。數組中的元素將使用各自的toLocaleString方法轉化成字串,這些字串將使用一個特定語言環境的字串(例如逗號)隔開
array.forEach((v, i, a) => {})
讓數組的每一項都執行一次給定的函數
v表示當前項的值,i表示當前索引,a表示數組本身
forEach遍曆的範圍在第一次調用 callback前就會確定。調用forEach後添加到數組中的項不會被 callback訪問到。如果已經存在的值被改變,則傳遞給 callback的值是 forEach遍曆到他們那一刻的值。已刪除的項不會被遍曆到。
array.entries()
返回一個Array Iterator對象,該對象包含數組中每一個索引的索引值對
var arr = ["a", "b", "c"];var eArr = arr.entries();console.log(eArr.next().value); // [0, "a"]console.log(eArr.next().value); // [1, "b"]console.log(eArr.next().value); // [2, "c"]
array.keys()
返回一個數組索引的迭代器(類似於array.entries()方法)
es6常用數組操作及技巧匯總