定義數組
const array = [1, 2, 3];
// 或者
const array = new Array();
array[0] = '1';
檢測數組
Array.isArray([]); // true
Array.isArray(undefined); // false;
array instanceof Array; // true 檢測對象的原型鏈是否指向構造函數的prototype對象
array.constructor === Array; // true
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
//注意:typeof []; // "object" 不可以用此方法檢查!!!
常用方法
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
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。
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);
}
});
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為[]
小結
push、 shift、 pop、 unshift、 reverse、 sort、 splice方法會對原來的數組進行修改,其他的數組操作方法只有返回值不同,對原數組都沒有影響,即原數組不變。