JS數組方法彙總

工具類方法

Array.from() :從一個相似數組或者可迭代對象中建立一個新的數組實例。
用一種更通俗易懂的方式來講,就是Array.from方法用於將兩類對象轉爲真正數組:類數組對象(array-like object)和可遍歷(iterable)的對象。
實際應用中,常見的類數組對象是 DOM 操做返回的 NodeList 集合,以及函數內部的arguments對象。Array.from均可以將它們轉爲真正的數組。
語法:Array.from(arrayLike[, mapFn[, thisArg]])
參數:
arrayLike 想要轉換成數組的僞數組對象或可迭代對象。
mapFn (可選參數) 若是指定了該參數,新數組中的每一個元素會執行該回調函數。
thisArg (可選參數) 可選參數,執行回調函數 mapFn 時 this 對象。
返回值: 一個新的數組實例算法

// arguments對象
function foo() {
  var args = Array.from(arguments);
  // ...
}
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);      
// [2, 4, 6]

Array.isArray() 用於肯定傳遞的值是不是一個 Array
語法:Array.isArray(obj)
參數:obj 須要檢測的值;
返回值:若是對象是 Array,則爲true; 不然爲false數組

Array.isArray([1, 2, 3]);  
// true
Array.isArray({foo: 123}); 
// false
Array.isArray("foobar");   
// false
Array.isArray(undefined);  
// false

Array.of方法用於將一組值,轉換爲數組
語法:Array.of(element0[, element1[, ...[, elementN]]])
參數:
elementN
任意個參數,將按順序成爲返回數組中的元素。
返回值:新的 Array 實例。
Array.of 和構造函數Array的區別瀏覽器

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

Array方法沒有參數、一個參數、三個參數時,返回結果都不同。只有當參數個數很多於 2 個時,Array()纔會返回由參數組成的新數組。參數個數只有一個時,其實是指定數組的長度。
Array.of基本上能夠用來替代Array()或new Array(),而且不存在因爲參數不一樣而致使的重載。它的行爲很是統一。函數

遍歷方法

Array.prototype.forEach:對數組的每一個元素執行一次提供的函數
語法:工具

array.forEach(callback(currentValue, index, array){
    //do something
}, this)

參數:
callback: 爲數組中每一個元素執行的函數,該函數接收下面3個參數;
currentValue: 當前數組元素;
index(可選): 當前數組索引;
array(可選): 被遍歷的數組自己;
this(可選): 當執行callback回調函數時用做this的值(參考對象)
返回值:undefined
示例:測試

// 打印每一個數組元素
function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}

Array.prototype.map(): 建立一個新數組,其結果是該數組中的每一個元素都調用一個提供的函數後返回的結果
語法:this

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array }[, 
thisArg])

參數:
callback:生成新數組元素的函數,有下面3個參數:
currentValue: 當前數組元素;
index(可選): 當前數組索引;
array(可選): 被遍歷的數組自己;
thisArg(可選): 當執行callback回調函數時用做this的值(參考對象)
返回值:一個新數組,每一個元素都是回調函數的結果。
示例:prototype

// 求數組中每一個元素的平方根
let arr = [1, 4, 9];
let new_arr = arr.map(currentValue => {
  return Math.sqrt(currentValue)
})
console.log(new_arr)

Array.prototype.reduce():reduce方法把一個函數做用在數組的全部元素。這個函數必須接收至少兩個參數,reduce()把函數的返回結果繼續和數組的下一個元素作累積計算
語法:code

arr.reduce(function callback(accumulator, currentValue[, currentIndex, array]) {
  // coding...
}[, initialValue)

參數:
callback: 執行數組中每一個值的函數,包含四個參數:
accumulator: 函數回調的返回值;它是上一次調用回調時返回的累積值,或initialValue(見於下方)。
currentValue: 數組正在處理的元素。
currentIndex: 數組中正在處理的當前元素的索引。若是提供了initialValue,則索引號未0,不然索引爲1。
array: 調用reduce()的數組。
initialValue: 做爲第一次調用 callback函數時的第一個參數的值。 若是沒有提供初始值,則將使用數組中的第一個元素。 在沒有初始值的空數組上調用 reduce 將報錯。
返回值:函數累計處理的結果。
示例:對象

// 求數組中每一個元素的和
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function (x, y) {
  return x + y;
}
// 10

Array.prototype.reduceRight():reduceRight方法把一個函數做用在數組的全部元素。這個函數必須接收至少兩個參數,reduceRight()把函數的返回結果繼續和數組的下一個元素作累積計算。和reduce不一樣的是,reduceRight的遍歷順序是從右到左。


Array.prototype.every(): every方法測試數組的全部元素是否都經過了指定元素的測試。
語法:

arr.erery(callback[, thisArg])

參數:
callback:用來測試每一個元素的函數。
thisArg:執行callback時內部指定的this值。
示例:

var arr = [1, 2, 3, 4, 11];
var passed = arr.every(function (x) {
  return x < 10;
}
// passed is false

Array.prototype.some():some方法測試數組的全部元素中是否有經過測試的。
語法:

arr.some(callback[, thisArg])

參數:
callback:用來測試每一個元素的函數。
thisArg:執行callback時內部指定的this值。
示例:

var arr = [1, 2, 3, 4, 10];
var passed = arr.some(function (x) {
  return x < 10;
}
// passed is true

Array.prototype.filter(): filter()方法建立一個數組,其包含經過所提供函數實現的測試的全部元素。
語法:

var new_array = arr.filter(callback(element[, index[, array]])[, thisArg])

參數:
callback
用來測試數組的每一個元素的函數。調用時使用參數(element, index, array)。
返回true表示保留該元素(經過測試),false則不保留,它接受三個參數:
element 當前在數組中處理的元素
index(可選) 正在處理元素在數組中的索引
array(可選) 調用了filter的數組
thisArg(可選) 執行callback時的用於 this 的值

示例:

var filtered = [12, 5, 8, 130, 44].filter(currentValue => {
  return currentValue > 10;
});
// filtered is [12, 130, 44]

Array.prototype.keys(): 對數組鍵名(也就是索引值)的遍歷,返回一個遍歷器對象。
Array.prototype.value(): 對數組鍵值(也就是數組元素)的遍歷,返回一個遍歷器對象。
Array.prototype.entries: 對數組鍵值對(索引值,對應數組元素)的遍歷,返回一個遍歷器對象。

直接上示例代碼:

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

查找方法

Array.prototype.find(): 用於找出第一個知足提供的回調函數的數組成員。全部數組成員依次執行該回調函數,直到找出第一個返回值爲true的成員,而後返回該成員。不然返回undefined。
Array.prototype.findIndex():用於找出第一個知足提供的回調函數的數組成員。全部數組成員依次執行該回調函數,直到找出第一個返回值爲true的成員,而後返回該成員的位置(也就是索引)。不然返回-1。
語法:

arr.find(callback[, thisArg]);
arr.findIndex(callback[, thisArg]);

參數:
callback
針對數組中的每一個元素, 都會執行該回調函數, 執行時會自動傳入下面三個參數:
element 當前元素。
index 當前元素的索引。
array 調用findIndex的數組。
thisArg 可選。執行callback時做爲this對象的值.

示例:

[1, 5, 10, 15].find(function(value, index, arr) {
  return value % 2 == 0;
}) // 10
[1, 5, 10, 15].find(function(value, index, arr) {
  return value % 2 == 0;
}) // 2

Array.prototype.indexOf:indexOf方法返回在數組中能夠找到一個給定元素的第一個索引,若是不存在,則返回-1。
Array.prototype.lastIndexOf:lastIndexOf方法返回在數組中能夠找到一個給定元素的最後一個索引(從數組的後面向前查找),若是不存在,則返回-1。
語法:

arr.indexOf(searchElement[, fromIndex = 0])
arr.lastIndexOf(searchElement[, fromIndex = 0])

參數:
searchElement 要查找的元素
fromIndex 開始查找的位置(對indexOf而言)或者開始逆向查找的位置(對lastIndexOf而言)
示例:

var indexof = [1, 5, 10, 5].indexOf(5) // 1
var lastindexof = [1, 5, 10, 5].indexOf(5) // 3

Array.prototype.includes(): includes() 方法用來判斷一個數組是否包含一個指定的值,根據狀況,若是包含則返回 true,不然返回false。
語法:

arr.includes(searchElement, fromIndex)

參數:
searchElement 須要查找的元素值。
fromIndex 可選 從該索引處開始查找 searchElement。若是爲負值,則按升序從 array.length - fromIndex 的索引開始搜索。默認爲 0。

增刪元素方法

Array.prototype.pop: 從數組中刪除最後一個元素,並返回該元素的值。此方法改變數組的長度。
Array.prototype.push: 將一個或多個元素添加到數組的末尾,並返回該數組的新長度。
示例:

// pop
let myFish = ["angel", "clown", "mandarin", "surgeon"];

let popped = myFish.pop();

console.log(myFish); 
// ["angel", "clown", "mandarin"]

console.log(popped); 
// surgeon

// push
var sports = ["soccer", "baseball"];
var total = sports.push("football", "swimming");

console.log(sports); 
// ["soccer", "baseball", "football", "swimming"]

console.log(total);  
// 4

Array.prototype.shift(): 從數組中刪除第一個元素,並返回該元素的值。此方法更改數組的長度。
Array.prototype.unshift(): 將一個或多個元素添加到數組的開頭,並返回該數組的新長度。
示例:

// shift
let myFish = ["angel", "clown", "mandarin", "surgeon"];

let shift_length = myFish.shift();

console.log(myFish); 
// ["clown", "mandarin", "surgeon"]

console.log(shift_length); 
// angel

// unshift
let sports = ["soccer", "baseball"];
let unshift_length = sports.unshift("football", "swimming");

console.log(sports); 
// ["football", "swimming", "soccer", "baseball"]

Array.prototype.splice: 經過刪除現有元素和/或添加新元素來更改一個數組的內容
語法:array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

參數:
start​:指定修改的開始位置(從0開始計數)
deleteCount:可選 指定要刪除的數組元素的個數,若是省略該參數,則從start開始的全部數組元素都被刪除(包括第start位)
item1, item2, ... : 可選,要添加進數組的元素,若是省略該參數,則只刪除數組元素
返回值:
若是沒有刪除元素,則返回空數組。由被刪除的數組元素組成的一個數組。若是隻刪除了一個元素,則返回只包含一個元素的數組。
示例:

var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myFish.splice(3, 1, 'big', 'small');
console.log(myFish);
console.log(removed)
// > Array ["angel", "clown", "drum", "big", "small", "sturgeon"]
// > Array ["mandarin"]

拼接/截取方法

Array.prototype.concat(): 拼接兩個或者多個數組,此方法不會修改原數組,而是返回一個新的數組。
示例:

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var new_arr = arr1.concat(arr2);
// new_arr [1, 2, 3, 4, 5, 6]

Array.prototype.slice(): 返回一個新的數組對象,這一對象是一個由 begin和end(不包括end)決定的原數組的淺拷貝。原始數組不會被改變。
語法:arr.slice(begin, end);
參數:
begin: 可選 從該索引處開始提取原數組中的元素,若是省略該參數,則從0開始。
end: 可選 從該索引處結束提取原數組中的元素,若是省略該參數,則會一直提取到原數組末尾。
示例:

var arr = [1, 2, 3, 4, 5, 6];
var sub_arr = arr.splice(1, 4);
// sub_arr [2, 3, 4]

排序方法

Array.prototype.reverse(): 將數組中元素的位置顛倒,第一個數組元素成爲最後一個數組元素,最後一個數組元素成爲第一個。
示例:

var arr = [1, 2, 3, 4, 5, 6];
arr.reverse();
// arr -> [6, 5, 4, 3, 2, 1]

Array.prototype.sort():MDN給出的定義是用原地算法對數組的元素進行排序,並返回數組。排序不必定是穩定的。默認排序順序是根據字符串Unicode碼點。具體是咋排的我也不知道,個人理解就是按照字符串的Unicode碼點進行排序的。
語法:arr.sort([compareFunction])
參數:
compareFunction: 用來指定按某種順序進行排列的函數。若是省略,元素按照轉換爲的字符串的各個字符的Unicode位點進行排序;若是不省略 compareFunction ,那麼數組會按照調用該函數的返回值排序。即 a 和 b 是兩個將要被比較的元素:

  • 若是 compareFunction(a, b) 小於 0 ,那麼 a 會被排列到 b 以前;
  • 若是 compareFunction(a, b) 等於 0 , a 和 b 的相對位置不變。備註: ECMAScript
    標準並不保證這一行爲,並且也不是全部瀏覽器都會遵照(例如 Mozilla 在 2003 年以前的版本);
  • 若是 compareFunction(a, b) 大於 0 , b 會被排列到 a 以前。
  • compareFunction(a, b) 必須老是對相同的輸入返回相同的比較結果,不然排序的結果將是不肯定的。

示例:

//升序
function sort_increase(a, b) {
 return a - b
}
// 降序
function sort_decrease(a, b) {
 return b - a
}
var arr = [3, 0 ,6 ,2 ,4 ,7]
arr.sort(sort_increase)
console.log(arr)

arr.sort(sort_decrease)
console.log(arr)

// > Array [7, 6, 4, 3, 2, 0]
// > Array [0, 2, 3, 4, 6, 7]

其餘

Array.prototype.copyWith():在當前數組內部,將指定位置的成員複製到其餘位置(會覆蓋原有成員),而後返回當前數組。也就是說,這個方法會修改原有數組。
語法:arr.prototype.copyWith(target, start = 0, end = this.length)
參數:
target(必需):從該位置開始替換數據。若是爲負值,表示倒數。
start(可選):從該位置開始讀取數據,默認爲 0。若是爲負值,表示倒數。
end(可選):到該位置前中止讀取數據,默認等於數組長度。若是爲負值,表示倒數。
示例:

[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

Array.prototype.fill(): 使用給定值,填充一個數組。這個方法會修改原有數組。

語法:arr.fill(value[, start[, end]])
參數:
value 用來填充數組元素的值。
start 可選 起始索引,默認值爲0。
end 可選 終止索引(不包括該位置),默認值爲 this.length。
示例:

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]

Array.protytye.join(): 一個數組(或一個類數組對象)的全部元素鏈接成一個字符串並返回這個字符串。
語法:arr.join(separator)
參數:
separator 指定一個字符串來分隔數組的每一個元素,若是省略(),數組元素用逗號分隔。默認爲 ","。


Array.prototype.toLocalString(): 返回一個字符串表示數組中的元素。數組中的元素將使用各自的 toLocaleString 方法轉成字符串,這些字符串將使用一個特定語言環境的字符串(例如一個逗號 ",")隔開。
Array.prototype.toString(): 返回一個字符串,表示指定的數組及其元素.

相關文章
相關標籤/搜索