【ES6】操作数组的常用方法有这些就够了
(一)陣列的建立
-
使用
Array
陣列的方式
new Array();// //建立一個數組 new Array([size]);// 建立一個數組並指定長度,注意不是上限,是長度 new Array(element0, element1, ..., elementn);// 建立一個數組並賦值 const array = new Array(); array[0] = '1';
- 採用字面量的方法
const array = []; //建立一個空陣列 const array2 = [1, 2, 3]; //建立一個有三個元素的陣列
(二)陣列自帶屬性
constructor // 返回建立陣列物件的原型函式 length // 返回陣列物件的長度 prototype // 可以增加陣列的原型方法和屬性
(三)檢測是否為陣列
-
使用
instanceof
方法
instanceof
用於判斷一個變數是否是某個物件的例項
const array = new Array(); array instanceof Array; //true
-
使用
constructor
屬性
constructor
屬性返回對建立此物件的陣列函式的引用,就是返回物件相對應的建構函式。
const array = new Array(); array.constructor === Array; // true
-
使用
isArray()
方法
對支援isArray
的瀏覽器,直接使用isArray
方法。
const array = new Array(); Array.isArray(array); //true
如果瀏覽器不支援Array.isArray()
則需進行必要判斷。
/** * 判斷一個物件是否是陣列,引數不是物件或者不是陣列,返回false * * @param {Object} arg 需要測試是否為陣列的物件 * @return {Boolean} 傳入引數是陣列返回true,否則返回false */ function isArray(arg) { if (typeof arg === 'object') { return Object.prototype.toString.call(arg) === '[object Array]'; } return false; }
(四)陣列元素的增加與刪除
-
array.push(e1, e2, ...eN)
將一個或多個元素新增到陣列的末尾,並返回新陣列的長度。
const array = [1, 2, 3]; const length = array.push(4, 5); // array: [1, 2, 3, 4, 5]; length: 5
-
array.unshift(e1, e2, ...eN)
將一個或多個元素新增到陣列的開頭,並返回新陣列的長度。
const array = [1, 2, 3]; const length = array.unshift(4, 5); // array: [ 4, 5, 1, 2, 3]; length: 5
-
array.pop()
從陣列中刪除最後一個元素,並返回最後一個元素的值,原陣列的最後一個元素被刪除。陣列為空時返回undefined。
const array = [1, 2, 3]; const poped = array.pop(); // array: [1, 2]; poped: 3
-
array.shift()
刪除陣列的第一個元素,並返回第一個元素,原陣列的第一個元素被刪除。陣列為空返回undefined。
const array = [1, 2, 3]; const shifted = array.shift(); // array: [2, 3]; shifted: 1
-
array.splice(start[, deleteCount, item1, item2, ...])
從陣列中新增/刪除元素,返回值是由被刪除的元素組成的一個新的陣列,如果只刪除了一個元素,則返回只包含一個元素的陣列。如果沒有刪除元素,則返回空陣列。
-
start
指定修改的開始位置(從0計數)。如果超出了陣列的長度,則從陣列末尾開始新增內容;如果是負值,則表示從陣列末位開始的第幾位(從1計數)。 -
deleteCount
(可選),從start
位置開始要刪除的元素個數。如果deleteCount
是 0,則不移除元素。這種情況下,至少應新增一個新元素。如果deleteCount
大於start
之後的元素的總數,則從start
後面的元素都將被刪除(含第start
位)。 -
item1, item2, …
(可選),要新增進陣列的元素,從start
位置開始。如果不指定,則splice()
將只刪除陣列元素。
const array = [1, 2, 3, 4, 5]; const deleted = array.splice(2, 0, 6); // 在索引為2的位置插入6 // array 變為 [1, 2, 6, 3, 4, 5]; deleted為[]
(五)陣列與字串的相互轉化
- 陣列轉字串
array.join(separator=',')
將陣列中的元素通過separator
連線成字串,並返回該字串,separator預設為","。
const array = [1, 2, 3]; let str = array.join(','); // str: "1,2,3"
toLocaleString()
、toString()
、valueOf()
:可以看作是join()
的特殊用法,不常用。
- 字串轉陣列
string.split(separator,howmany)
用於把一個字串分割成字串陣列。
separator (必需),字串或正則表示式,從該引數指定的地方對字串進行分割。
howmany (可選),該引數可指定返回的陣列的最大長度。
let str = "abc,abcd,aaa"; let array = str.split(",");// 在每個逗號(,)處進行分解。 // array: [abc,abcd,aaa] const array1 = "helloworld"; let str1 = s1.split(''); //["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
(六)陣列的擷取和合並
-
陣列的擷取 -
array.slice(start, end)
方法
-
slice()
通過索引位置,從陣列中返回start
下標開始,直到end
下標結束(不包括 )的新陣列,該方法不會修改原陣列,只是返回一個新的子陣列 。 -
start
(必填),設定新陣列的起始位置(下標從0開始算起);如果是負數,則表示從陣列尾部開始算起(-1 指最後一個元素,-2 指倒數第二個元素,以此類推)。 -
end
(可選),設定新陣列的結束位置;如果不填寫該引數,預設到陣列結尾;如果是負數,則表示從陣列尾部開始算起(-1 指最後一個元素,-2
指倒數第二個元素,以此類推)。
// 獲取僅包含最後一個元素的子陣列 let array = [1,2,3,4,5]; array.slice(-1); // [5] // 獲取不包含最後一個元素的子陣列 let array2 = [1,2,3,4,5]; array2.slice(0, -1); // [1,2,3,4]
該方法並不會修改陣列,而是返回一個子陣列。如果想刪除陣列中的一段元素,應該使用方法array.splice()
。
-
陣列的合併 -
array.concat([item1[, item2[, . . . [,itemN]]]])
方法
conact()
是將多個數組(也可以是字串,或者是陣列和字串的混合)連線為一個數組,返回連線好的新的陣列。
const array = [1,2].concat(['a', 'b'], ['name']); // [1, 2, "a", "b", "name"]
(七)陣列元素的排序
-
array.sort()
方法
sort()
方法用於對陣列的元素進行排序,並返回原陣列
。如果不帶引數,按照字串UniCode
碼的順序進行排序。
const array = ['a', 'd', 'c', 'b']; array.sort();//['a', 'b', 'c', 'd']
為sort()
中傳入排序規則函式可實現自定義排序。
排序函式規則:(1)傳兩個形參 ;(2)當返回值為正數時,交換傳入兩形參在陣列中位置 。
按照數值大小進行排序-升序
[1, 8, 5].sort((a, b) => { return a-b; // 從小到大排序 }); // [1, 5, 8]
按照數值大小進行排序-降序
[1, 8, 5].sort((a, b) => { return b-a; // 從大到小排序 }); // [8, 5, 1]
-
array.reverse()
方法reverse()
方法將陣列中元素的位置顛倒 ,第一個陣列元素成為最後一個數組元素,最後一個數組元素成為第一個。在原陣列上操作,然後返回原陣列 。
let arr = [1,2,3,4,5] console.log(arr.reverse())// [5,4,3,2,1] console.log(arr)// [5,4,3,2,1]
陣列的sort()
和reverse()
方法都對原陣列進行了修改。
(八)元素在陣列中的位置
-
indexOf()
與lastIndexOf()
-
indexOf(searchElement[, fromIndex = 0])
方法返回某個指定的字串值在字串中首次出現的位置 。 -
lastIndexOf(searchElement[, fromIndex = 0])
方法返回一個指定的字串值最後出現的位置 ,在一個字串中的指定位置從後向前搜尋。 -
這兩個方法都接受兩個引數:
searchElement
:要查詢的元素;fromIndex
:開始查詢的索引位置。 - 這兩個方法都返回查詢的項在陣列中的位置,或者在沒找到的情況下返回-1 。
[2, 9, 7, 8, 9].indexOf(9); // 1 [2, 9, 7, 8, 9].lastIndexOf(9); // 4
-
find()
與findIndex()
(1)find(callback[, thisArg])
方法,用於找出第一個符合條件的陣列元素
。它的引數是一個回撥函式,所有陣列成員依次執行該回調函式,直到找出第一個返回值為true的成員,然後返回該成員。如果沒有符合條件的成員,則返回undefined
。
[1, 4, -5, 10].find((n) => n < 0) // -5
find()
方法的回撥函式可以接受三個引數,依次為當前的值、當前的位置和原陣列。
[1, 5, 10, 15].find(function(value, index, arr) { return value > 9; }) // 10
(2)findIndex(callback[, thisArg])
返回第一個符合條件的陣列成員的位置,如果所有成員都不符合條件,則返回-1。
[1, 5, 10, 15].findIndex(function(value, index, arr) { return value > 9; }) // 2
這兩個方法都可以接受第二個引數,用來繫結回撥函式的this
物件。
function f(v){ return v > this.age; } let person = {name: 'John', age: 20}; [10, 12, 26, 15].find(f, person);// 26
-
includes(searchElement[, fromIndex = 0])
方法返回一個布林值,表示某個陣列是否包含給定的值。
這個方法都接受兩個引數:searchElement
:要查詢的元素;fromIndex
:開始查詢的索引位置。
[1, 2, 3].includes(2)// true [1, 2, 3].includes(3, 3);// false [1, 2, 3].includes(3, -1); // true
(九)陣列的遍歷與迭代
-
array.filter(callback, thisArg)
方法使用指定的函式測試所有元素,並建立一個包含所有通過測試的元素的新陣列。
引數說明:
-
callback
用來測試陣列的每個元素的函式,返回true
表示保留該元素(通過測試),false
則不保留。 -
thisArg
可選。執行callback
時的用於this
的值。
// 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];
-
array.every(callback[, thisArg])
方法檢測陣列中的每一個元素是否都通過了callback
測試,全部通過返回true
,否則返回false
。
// callback定義如下: element:當前元素值;index:當前元素下標; array:當前陣列 function callback(element, index, array) { // callback函式必須返回true或者false告知every是否通過測試 return true || false; } let a = [1, 2, 3, 4, 5]; let b = a.every((item) => { return item > 0; }); let c = a.every((item) => { return item > 1; }); console.log(b); // true console.log(c); // false
-
array.some(callback[, thisArg])
判斷陣列中是否包含可以通過callback
測試的元素,與every
不同的是,這裡只要某一個元素通過測試,即返回true
。callback
定義同上。
[2, 5, 8, 1, 4].some(item => item > 6); // true
-
array.map(callback[, thisArg])
方法返回一個由原陣列中的每個元素呼叫callback
函式後的返回值組成的新陣列。
let a = [1, 2, 3, 4, 5]; let b = a.filter((item) => { return item > 3; }); console.log(b); // [4 ,5] let bb = []; a.map((item) => { if (item > 3) { bb.push(item); } }); console.log(bb);// [4, 5] let bbb = a.map((item) => { return item + 1; }); console.log(bbb);// [2, 3, 4, 5, 6]
-
array.forEach(callbak)
為陣列的每個元素執行對應的方法。
// callback定義如下: element:當前元素值;index:當前元素下標; array:當前陣列 let a = [1, 2, 3, 4, 5]; let b = []; a.forEach((item) => { b.push(item + 1); }); console.log(b); // [2,3,4,5,6]
-
遍歷陣列的方法:
entries()
、values()
、keys()
這三個方法都是返回一個遍歷器物件,可用for...of
迴圈遍歷,唯一區別:keys()
是對鍵名的遍歷、values()
對鍵值的遍歷、entries()
是對鍵值對的遍歷。
for(let item of ['a','b'].keys()){ consloe.log(item); //0 //1 } for(let item of ['a','b'].values()){ consloe.log(item); //'a' //'b' } let arr4 = [0,1]; for(let item of arr4.entries()){ console.log(item); //[0, 0] //[1, 1] } for(let [index,item] of arr4.entries()){ console.log(index+':'+item); //0:0 //1:1 }
-
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) { }
以上callback
的引數中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"];
(十)其他方法
-
Array.from()
方法
Array.from()
方法是用於將類似陣列的物件(即有length屬性的物件)和可遍歷物件轉為真正的陣列。
比如,使用·Array.from()·方法,可以輕鬆將·JSON·陣列格式轉為陣列。
let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
-
Array.of()
方法
Array.of()
方法是將一組值轉變為陣列。
let arr0 = Array.of(1,2,33,5); console.log(arr0);//[1,2,33,5] let arr1 = Array.of('你好','hello'); console.log(arr1);//["你好", "hello"]
(十一)擴充套件運算子
擴充套件運算子(spread
)是三個點(...
)。它好比rest
引數的逆運算,將一個數組轉為用逗號分隔的引數序列
。
console.log(...[1, 2, 3]) // 1 2 3 console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5
該運算子主要用於函式呼叫 。
function add(x, y) { return x + y; } const numbers = [4, 38]; add(...numbers) // 42
注意,擴充套件運算子如果
放在括號中,JavaScript/">JavaScript
引擎就會認為這是函式呼叫
,就會報錯。
(...[1,2]) // Uncaught SyntaxError: Unexpected number console.log((...[1,2])) // Uncaught SyntaxError: Unexpected number console.log(...[1, 2]) // 1,2