javascript
JS标准内置对象 数组 的 34 个方法
先放一個語雀的鏈接:
https://www.yuque.com/docs/share/13314a2f-05c0-4de6-8d61-8acd9e566ad4?# 《JS內(nèi)置對象 Array》
1. at()接收一個整數(shù)值并返回該索引對應的元素
at() 方法接收一個整數(shù)值并返回該索引對應的元素,允許正數(shù)和負數(shù)。負整數(shù)從數(shù)組中的最后一個元素開始倒數(shù)。
at() 方法是通用的。其僅期望 this 具有 length 屬性和以整數(shù)為鍵的屬性。
const array1 = [5, 12, 8, 130, 44];let index = 2;console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`); // expected output: "Using an index of 2 the item returned is 8"index = -2;console.log(`Using an index of ${index} item returned is ${array1.at(index)}`); // expected output: "Using an index of -2 item returned is 130"這個示例比較了選擇 Array 中倒數(shù)第二個元素的不同方法。凸顯了 at() 方法的簡潔性和可讀性。
// 數(shù)組及數(shù)組元素 const colors = ['red', 'green', 'blue'];// 使用長度屬性 const lengthWay = colors[colors.length-2]; console.log(lengthWay); // 輸出:'green'// 使用 slice() 方法。注意會返回一個數(shù)組 const sliceWay = colors.slice(-2, -1); console.log(sliceWay[0]); // 輸出:'green'// 使用 at() 方法 const atWay = colors.at(-2); console.log(atWay); // 輸出:'green'2. concat()合并兩個或多個數(shù)組
concat() 方法用于合并兩個或多個數(shù)組。此方法不會更改現(xiàn)有數(shù)組,而是返回一個新數(shù)組。
舉例: const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2);console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]語法: concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN)參數(shù) valueN 可選 數(shù)組和/或值,將被合并到一個新的數(shù)組中。如果省略了所有 valueN 參數(shù), 則 concat 會返回調(diào)用此方法的現(xiàn)存數(shù)組的一個淺拷貝。3.copyWithin( ) 淺復制數(shù)組的一部分到同一數(shù)組中的另一個位置,并返回它
copyWithin() 方法淺復制數(shù)組的一部分到同一數(shù)組中的另一個位置,并返回它,不會改變原數(shù)組的長度。copyWithin 函數(shù)被設計為通用式的,其不要求其 this 值必須是一個數(shù)組對象。
const array1 = ['a', 'b', 'c', 'd', 'e'];// copy to index 0 the element at index 3 console.log(array1.copyWithin(0, 3, 4)); // expected output: Array ["d", "b", "c", "d", "e"]// copy to index 1 all elements from index 3 to the end console.log(array1.copyWithin(1, 3)); // expected output: Array ["d", "d", "e", "d", "e"]copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
target
0 為基底的索引,復制序列到該位置。如果是負數(shù),target 將從末尾開始計算。如果 target 大于等于 arr.length,將不會發(fā)生拷貝。如果 target 在 start 之后,復制的序列將被修改以符合 arr.length。
start
0 為基底的索引,開始復制元素的起始位置。如果是負數(shù),start 將從末尾開始計算。如果 start 被忽略,copyWithin 將會從 0 開始復制。
end
0 為基底的索引,開始復制元素的結(jié)束位置。copyWithin 將會拷貝到該位置,但不包括 end 這個位置的元素。如果是負數(shù), end 將從末尾開始計算。如果 end 被忽略,copyWithin 方法將會一直復制至數(shù)組結(jié)尾(默認為 arr.length)
4. entries( ) 返回一個新的數(shù)組迭代器對象
entries() 方法返回一個新的數(shù)組迭代器對象,該對象包含數(shù)組中每個索引的鍵/值對。
const array1 = ['a', 'b', 'c'];const iterator1 = array1.entries();console.log(iterator1.next().value); // expected output: Array [0, "a"]console.log(iterator1.next().value); // expected output: Array [1, "b"]entries() 方法讀取 this 的 length 屬性,然后訪問每個整數(shù)索引。
const arrayLike = {length: 3,0: "a",1: "b",2: "c", }; for (const entry of Array.prototype.entries.call(arrayLike)) {console.log(entry); } // [ 0, 'a' ] // [ 1, 'b' ] // [ 2, 'c' ]5. every () 測試一個數(shù)組內(nèi)的所有元素是否都能通過某個指定函數(shù)的測試。
every() 方法測試一個數(shù)組內(nèi)的所有元素是否都能通過某個指定函數(shù)的測試。它返回一個布爾值。若收到一個空數(shù)組,此方法在任何情況下都會返回 true。
const isBelowThreshold = (currentValue) => currentValue < 40;const array1 = [1, 30, 39, 29, 10, 13];console.log(array1.every(isBelowThreshold)); // expected output: true6. fill () 用一個固定值填充一個數(shù)組中從起始索引到終止索引內(nèi)的全部元素。
fill() 方法用一個固定值填充一個數(shù)組中從起始索引到終止索引內(nèi)的全部元素。不包括終止索引。fill 方法故意被設計成通用方法,該方法不要求 this 是數(shù)組對象。當一個對象被傳遞給 fill 方法的時候,填充數(shù)組的是這個對象的引用。
const array1 = [1, 2, 3, 4];// fill with 0 from position 2 until position 4 console.log(array1.fill(0, 2, 4)); // expected output: [1, 2, 0, 0]// fill with 5 from position 1 console.log(array1.fill(5, 1)); // expected output: [1, 5, 5, 5]console.log(array1.fill(6)); // expected output: [6, 6, 6, 6]語法: fill(value) fill(value, start) fill(value, start, end)參數(shù):value 用來填充數(shù)組元素的值。 start 可選 起始索引,默認值為 0。 end 可選 終止索引,默認值為 arr.length。返回值: 修改后的數(shù)組。7. filter () 創(chuàng)建給定數(shù)組一部分的淺拷貝,過濾數(shù)組。
filter() 方法創(chuàng)建給定數(shù)組一部分的淺拷貝,其包含通過所提供函數(shù)實現(xiàn)的測試的所有元素。filter() 不會改變原數(shù)組,而是返回一個新數(shù)組。
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];const result = words.filter(word => word.length > 6);console.log(result); // expected output: Array ["exuberant", "destruction", "present"]示例
使用 filter() 創(chuàng)建了一個新數(shù)組,該數(shù)組的元素由原數(shù)組中值大于 10 的元素組成。
function isBigEnough(value) {return value >= 10; }const filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]8. find () 返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。
find() 方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。否則返回 undefined。find 方法不會改變數(shù)組。
const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found); // expected output: 12- 如果需要在數(shù)組中找到對應元素的索引,請使用 findIndex()。
- 如果需要查找某個值的索引,請使用 Array.prototype.indexOf()。(它類似于 Array.prototype.indexOf(),但只是檢查每個元素是否與值相等,而不是使用測試函數(shù)。)
- 如果需要查找數(shù)組中是否存在值,請使用 Array.prototype.includes()。同樣,它檢查每個元素是否與值相等,而不是使用測試函數(shù)。
- 如果需要查找是否有元素滿足所提供的測試函數(shù),請使用 Array.prototype.some()。
語法:
// 箭頭函數(shù) find((element) => { /* … */ } ) find((element, index) => { /* … */ } ) find((element, index, array) => { /* … */ } )// 回調(diào)函數(shù) find(callbackFn) find(callbackFn, thisArg)// 內(nèi)聯(lián)回調(diào)函數(shù) find(function(element) { /* … */ }) find(function(element, index) { /* … */ }) find(function(element, index, array){ /* … */ }) find(function(element, index, array) { /* … */ }, thisArg)參數(shù): callbackFn 在數(shù)組每一項上執(zhí)行的函數(shù),接收 3 個參數(shù): element 當前遍歷到的元素。 index 當前遍歷到的索引。 array 數(shù)組本身。返回值: 數(shù)組中第一個滿足所提供測試函數(shù)的元素的值,否則返回 undefined。示例:
9. findIndex () 數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。
findIndex()方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。若沒有找到對應元素則返回 -1。
const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.findIndex(isLargeNumber)); // expected output: 310. findLast ()數(shù)組中滿足提供的測試函數(shù)條件的最后一個元素的值。
findLast() 方法返回數(shù)組中滿足提供的測試函數(shù)條件的最后一個元素的值。如果沒有找到對應元素,則返回 undefined。
const array1 = [5, 12, 50, 130, 44];const found = array1.findLast((element) => element > 45);console.log(found); // expected output: 13011. findLastIndex () 數(shù)組中滿足提供的測試函數(shù)的最后一個元素的索引。
findLastIndex() 方法返回數(shù)組中滿足提供的測試函數(shù)條件的最后一個元素的索引。若沒有找到對應元素,則返回 -1。
const array1 = [5, 12, 50, 130, 44];const isLargeNumber = (element) => element > 45;console.log(array1.findLastIndex(isLargeNumber)); // expected output: 3 (of element with value: 130)12. flat()按照一個可指定的深度遞歸遍歷數(shù)組,并返回新數(shù)組。
flat() 方法會按照一個可指定的深度遞歸遍歷數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個新數(shù)組返回。
const arr1 = [0, 1, 2, [3, 4]];console.log(arr1.flat()); // expected output: [0, 1, 2, 3, 4]const arr2 = [0, 1, 2, [[[3, 4]]]];console.log(arr2.flat(2)); // expected output: [0, 1, 2, [3, 4]]語法:
flat() flat(depth)參數(shù): depth 可選 指定要提取嵌套數(shù)組的結(jié)構(gòu)深度,默認值為 1。返回值: 一個包含將數(shù)組與子數(shù)組中所有元素的新數(shù)組。示例:
使用 flat(Infinity),可展開任意深度的嵌套數(shù)組
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4]var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]]var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]//使用 Infinity,可展開任意深度的嵌套數(shù)組 var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]flat() 方法會移除數(shù)組中的空項:
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]13. flatMap () 使用映射函數(shù)映射每個元素,然后將結(jié)果壓縮成一個新數(shù)組。
flatMap() 方法首先使用映射函數(shù)映射每個元素,然后將結(jié)果壓縮成一個新數(shù)組。它與 map 連著深度值為 1 的 flat 幾乎相同,但 flatMap 通常在合并成一種方法的效率稍微高一些。
const arr1 = [1, 2, [3], [4, 5], 6, []];const flattened = arr1.flatMap(num => num);console.log(flattened); // expected output: Array [1, 2, 3, 4, 5, 6]示例:
14. forEach () 對數(shù)組的每個元素執(zhí)行一次給定的函數(shù)。
forEach() 方法對數(shù)組的每個元素執(zhí)行一次給定的函數(shù)。
const array1 = ['a', 'b', 'c'];array1.forEach(element => console.log(element));// expected output: "a" // expected output: "b" // expected output: "c"
備注: 除了拋出異常以外,沒有辦法中止或跳出 forEach() 循環(huán)。如果你需要中止或跳出循環(huán),forEach() 方法不是應當使用的工具。
若你需要提前終止循環(huán),你可以使用:
- 一個簡單的 for 循環(huán)
- for...of / for...in 循環(huán)
- Array.prototype.every()
- Array.prototype.some()
- Array.prototype.find()
- Array.prototype.findIndex()
這些數(shù)組方法則可以對數(shù)組元素判斷,以便確定是否需要繼續(xù)遍歷:
- every()
- some()
- find()
- findIndex()
譯者注:只要條件允許,也可以使用 filter() 提前過濾出需要遍歷的部分,再用 forEach() 處理。
示例:
15. from () 對一個類似數(shù)組或可迭代對象創(chuàng)建一個新的,淺拷貝的數(shù)組實例。 把非數(shù)組->數(shù)組。
console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"]console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]語法:
// 箭頭函數(shù) Array.from(arrayLike, (element) => { /* … */ } ) Array.from(arrayLike, (element, index) => { /* … */ } )// 映射函數(shù) Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg)// 內(nèi)聯(lián)映射函數(shù) Array.from(arrayLike, function mapFn(element) { /* … */ }) Array.from(arrayLike, function mapFn(element, index) { /* … */ }) Array.from(arrayLike, function mapFn(element) { /* … */ }, thisArg) Array.from(arrayLike, function mapFn(element, index) { /* … */ }, thisArg)參數(shù): arrayLike 想要轉(zhuǎn)換成數(shù)組的偽數(shù)組對象或可迭代對象。mapFn 可選 如果指定了該參數(shù),新數(shù)組中的每個元素會執(zhí)行該回調(diào)函數(shù)。thisArg 可選 可選參數(shù),執(zhí)行回調(diào)函數(shù) mapFn 時 this 對象。返回值: 一個新的數(shù)組實例。示例:
16. includes() 判斷一個數(shù)組是否包含一個指定的值。
includes() 方法用來判斷一個數(shù)組是否包含一個指定的值,根據(jù)情況,如果包含則返回 true,否則返回 false。使用 includes() 比較字符串和字符時是區(qū)分大小寫的。
const array1 = [1, 2, 3];console.log(array1.includes(2)); // expected output: trueconst pets = ['cat', 'dog', 'bat'];console.log(pets.includes('cat')); // expected output: trueconsole.log(pets.includes('at')); // expected output: false語法:
includes(searchElement) includes(searchElement, fromIndex)參數(shù): searchElement 需要查找的元素值。fromIndex 可選 從fromIndex 索引處開始查找 searchElement。 如果為負值,則按升序從 array.length + fromIndex 的索引開始搜 (即使從末尾開始往前跳 fromIndex 的絕對值個索引,然后往后搜尋)。默認為 0。示例:
[1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, NaN].includes(NaN); // true17. indexOf() 返回在數(shù)組中可以找到給定元素的第一個索引。
indexOf() 方法返回在數(shù)組中可以找到給定元素的第一個索引,如果不存在,則返回 -1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison')); // expected output: 1// start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4console.log(beasts.indexOf('giraffe')); // expected output: -1語法:
indexOf(searchElement) indexOf(searchElement, fromIndex)參數(shù): searchElement 要查找的元素。 fromIndex 可選 開始查找的位置。如果該索引值大于或等于數(shù)組長度,意味著不會在數(shù)組里查找,返回 -1。如果參數(shù)中提供的索引值是一個負值,則將其作為數(shù)組末尾的一個抵消,即 -1 表示從最后一個元素開始查找,-2 表示從倒數(shù)第二個元素開始查找,以此類推。注意:如果參數(shù)中提供的索引值是一個負值,并不改變其查找順序,查找順序仍然是從前向后查詢數(shù)組。如果抵消后的索引值仍小于 0,則整個數(shù)組都將會被查詢。其默認值為 0。返回值: 首個被找到的元素在數(shù)組中的索引位置; 若沒有找到則返回 -1。示例:
18. isArray() 用于確定傳遞的值是否是一個 Array。
Array.isArray() 用于確定傳遞的值是否是一個數(shù)組。
Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false語法:
Array.isArray(value)參數(shù): value 需要檢測的值。返回值: 如果值是 Array,則為 true;否則為 false。示例:
// 下面的函數(shù)調(diào)用都返回 true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.isArray(new Array('a', 'b', 'c', 'd')) Array.isArray(new Array(3)); // 鮮為人知的事實:其實 Array.prototype 也是一個數(shù)組。 Array.isArray(Array.prototype);// 下面的函數(shù)調(diào)用都返回 false Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)) Array.isArray({ __proto__: Array.prototype });19. join() 將一個數(shù)組的所有元素連接成一個字符串并返回這個字符串。
join() 方法將一個數(shù)組(或一個類數(shù)組對象)的所有元素連接成一個字符串并返回這個字符串,用逗號或指定的分隔符字符串分隔。如果數(shù)組只有一個元素,那么將返回該元素而不使用分隔符。
const elements = ['Fire', 'Air', 'Water'];console.log(elements.join()); // expected output: "Fire,Air,Water"console.log(elements.join('')); // expected output: "FireAirWater"console.log(elements.join('-')); // expected output: "Fire-Air-Water"語法:
join() join(separator)參數(shù): separator 可選 指定一個字符串來分隔數(shù)組的每個元素。如果需要,將分隔符轉(zhuǎn)換為字符串。如果省略,數(shù)組元素用逗號(,)分隔。如果 separator 是空字符串(""),則所有元素之間都沒有任何字符。返回值: 一個所有數(shù)組元素連接的字符串。如果 arr.length 為 0,則返回空字符串。示例:
join() 將空槽視為 undefined,并產(chǎn)生額外的分隔符:
console.log([1, , 3].join()); // '1,,3' console.log([1, undefined, 3].join()); // '1,,3'20. keys() 返回一個包含數(shù)組中每個索引鍵的 Array Iterator 對象。
keys() 方法返回一個包含數(shù)組中每個索引鍵的 Array Iterator 對象。
const array1 = ['a', 'b', 'c']; const iterator = array1.keys();for (const key of iterator) {console.log(key); }// expected output: 0 // expected output: 1 // expected output: 2語法:
語法: keys()返回值: 一個新的 Array 迭代器對象。示例:
21. lastIndexOf() 返回指定元素在數(shù)組中的最后一個的索引。
lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或變量)在數(shù)組中的最后一個的索引,如果不存在則返回 -1。從數(shù)組的后面向前查找,從 fromIndex 處開始。
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];console.log(animals.lastIndexOf('Dodo')); // expected output: 3console.log(animals.lastIndexOf('Tiger')); // expected output: 1示例:
使用 lastIndexOf 查找到一個元素在數(shù)組中所有的索引(下標),并使用 push 將所有添加到另一個數(shù)組中。
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.lastIndexOf(element);while (idx != -1) {indices.push(idx);idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); }console.log(indices); // [4, 2, 0];22. map() 遍歷之后創(chuàng)建新數(shù)組。
map() 方法創(chuàng)建一個新數(shù)組,這個新數(shù)組由原數(shù)組中的每個元素都調(diào)用一次提供的函數(shù)后的返回值組成。因為 map 生成一個新數(shù)組,當你不打算使用返回的新數(shù)組卻使用 map 是違背設計初衷的,請用 forEach 或者 for-of 替代。
如果有以下情形,則不該使用 map:
- 你不打算使用返回的新數(shù)組;或
- 你沒有從回調(diào)函數(shù)中返回值。
示例:
23. pop() 從數(shù)組中刪除最后一個元素,并返回該元素的值。
pop() 方法從數(shù)組中刪除最后一個元素,并返回該元素的值。此方法會更改數(shù)組的長度。
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];console.log(plants.pop()); // expected output: "tomato"console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]plants.pop();console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage"]語法:
pop()返回值: 從數(shù)組中刪除的元素(當數(shù)組為空時返回undefined)。24. push() 將一個或多個元素添加到數(shù)組的末尾,并返回該數(shù)組的新長度。
push() 方法將一個或多個元素添加到數(shù)組的末尾,并返回該數(shù)組的新長度。
const animals = ['pigs', 'goats', 'sheep'];const count = animals.push('cows'); console.log(count); // expected output: 4 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"]animals.push('chickens', 'cats', 'dogs'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]語法:
push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN)參數(shù): elementN 被添加到數(shù)組末尾的元素。返回值: 當調(diào)用該方法時,新的 length 屬性值將被返回。
示例:
下面的代碼創(chuàng)建了 sports 數(shù)組,包含兩個元素,然后又把兩個元素添加給它。total 變量為數(shù)組的新長度值。
var sports = ["soccer", "baseball"]; var total = sports.push("football", "swimming");console.log(sports); // ["soccer", "baseball", "football", "swimming"]console.log(total); // 425. reduce() 迭代計算數(shù)組所有元素的總和。
reduce() 方法對數(shù)組中的每個元素按序執(zhí)行一個由您提供的 reducer 函數(shù),每一次運行 reducer 會將先前元素的計算結(jié)果作為參數(shù)傳入,最后將其結(jié)果匯總為單個返回值。
第一次執(zhí)行回調(diào)函數(shù)時,不存在“上一次的計算結(jié)果”。如果需要回調(diào)函數(shù)從數(shù)組索引為 0 的元素開始執(zhí)行,則需要傳遞初始值。否則,數(shù)組索引為 0 的元素將被作為初始值 initialValue,迭代器將從第二個元素開始執(zhí)行(索引為 1 而不是 0)。
const array1 = [1, 2, 3, 4];// 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce((previousValue, currentValue) => previousValue + currentValue,initialValue );console.log(sumWithInitial); // expected output: 10reducer 逐個遍歷數(shù)組元素,每一步都將當前元素的值與上一步的計算結(jié)果相加(上一步的計算結(jié)果是當前元素之前所有元素的總和)——直到?jīng)]有更多的元素被相加。
語法:
// 箭頭函數(shù) reduce((previousValue, currentValue) => { /* … */ } ) reduce((previousValue, currentValue, currentIndex) => { /* … */ } ) reduce((previousValue, currentValue, currentIndex, array) => { /* … */ } )reduce((previousValue, currentValue) => { /* … */ } , initialValue) reduce((previousValue, currentValue, currentIndex) => { /* … */ } , initialValue) reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue)// 回調(diào)函數(shù) reduce(callbackFn) reduce(callbackFn, initialValue)// 內(nèi)聯(lián)回調(diào)函數(shù) reduce(function(previousValue, currentValue) { /* … */ }) reduce(function(previousValue, currentValue, currentIndex) { /* … */ }) reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ })reduce(function(previousValue, currentValue) { /* … */ }, initialValue) reduce(function(previousValue, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ }, initialValue)參數(shù):
callbackFn
一個“reducer”函數(shù),包含四個參數(shù):
- previousValue:上一次調(diào)用 callbackFn 時的返回值。在第一次調(diào)用時,若指定了初始值 initialValue,其值則為 initialValue,否則為數(shù)組索引為 0 的元素 array[0]。
- currentValue:數(shù)組中正在處理的元素。在第一次調(diào)用時,若指定了初始值 initialValue,其值則為數(shù)組索引為 0 的元素 array[0],否則為 array[1]。
- currentIndex:數(shù)組中正在處理的元素的索引。若指定了初始值 initialValue,則起始索引號為 0,否則從索引 1 起始。
- array:用于遍歷的數(shù)組。
initialValue 可選
作為第一次調(diào)用 callback 函數(shù)時參數(shù) previousValue 的值。若指定了初始值 initialValue,則 currentValue 則將使用數(shù)組第一個元素;否則 previousValue 將使用數(shù)組第一個元素,而 currentValue 將使用數(shù)組第二個元素。
返回值:
使用“reducer”回調(diào)函數(shù)遍歷整個數(shù)組后的結(jié)果。
示例:
1. 求數(shù)組所有值的和
26. reverse() 將數(shù)組中元素的位置顛倒,并返回該數(shù)組。
reverse() 方法將數(shù)組中元素的位置顛倒,并返回該數(shù)組。數(shù)組的第一個元素會變成最后一個,數(shù)組的最后一個元素變成第一個。該方法會改變原數(shù)組。
const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // expected output: "array1:" Array ["one", "two", "three"]const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"]// Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // expected output: "array1:" Array ["three", "two", "one"]27. shift() 從數(shù)組中刪除第一個元素,并返回該元素的值。此方法更改數(shù)組的長度。
shift() 方法從數(shù)組中刪除第一個元素,并返回該元素的值。此方法更改數(shù)組的長度。
示例:
以下代碼顯示了刪除其第一個元素之前和之后的 myFish 數(shù)組。它還顯示已刪除的元素:
let myFish = ['angel', 'clown', 'mandarin', 'surgeon'];console.log('調(diào)用 shift 之前:' + myFish); // "調(diào)用 shift 之前:angel,clown,mandarin,surgeon"var shifted = myFish.shift();console.log('調(diào)用 shift 之后:' + myFish); // "調(diào)用 shift 之后:clown,mandarin,surgeon"console.log('被刪除的元素:' + shifted); // "被刪除的元素:angel"28. slice() 返回一個新的數(shù)組對象,原始數(shù)組不會被改變。
slice() 方法返回一個新的數(shù)組對象,這一對象是一個由 begin 和 end 決定的原數(shù)組的淺拷貝(包括 begin,不包括end)。原始數(shù)組不會被改變。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"]console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"]console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"]console.log(animals.slice(-2)); // expected output: Array ["duck", "elephant"]console.log(animals.slice(2, -1)); // expected output: Array ["camel", "duck"]console.log(animals.slice()); // expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
語法:
29. some() 測試數(shù)組中是不是至少有 1 個元素通過了被提供的函數(shù)測試。
some() 方法測試數(shù)組中是不是至少有 1 個元素通過了被提供的函數(shù)測試。它返回的是一個 Boolean 類型的值。如果用一個空數(shù)組進行測試,在任何情況下它返回的都是false。
const array = [1, 2, 3, 4, 5];// checks whether an element is even const even = (element) => element % 2 === 0;console.log(array.some(even)); // expected output: true示例:
30. sort() 排序,并返回數(shù)組。
sort() 方法用原地算法對數(shù)組的元素進行排序,并返回數(shù)組。默認排序順序是在將元素轉(zhuǎn)換為字符串,然后比較它們的 UTF-16 代碼單元值序列時構(gòu)建的。
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"]const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]語法:
// 無函數(shù) sort()// 箭頭函數(shù) sort((a, b) => { /* … */ } )// 比較函數(shù) sort(compareFn)// 內(nèi)聯(lián)比較函數(shù) sort(function compareFn(a, b) { /* … */ })參數(shù):
compareFn 可選 用來指定按某種順序進行排列的函數(shù)。 如果省略,元素按照轉(zhuǎn)換為的字符串的各個字符的 Unicode 位點進行排序。a 第一個用于比較的元素。b 第二個用于比較的元素。描述: 如果指明了 compareFn ,那么數(shù)組會按照調(diào)用該函數(shù)的返回值排序。 即 a 和 b 是兩個將要被比較的元素:如果 compareFn(a, b) 大于 0,b 會被排列到 a 之前。 如果 compareFn(a, b) 小于 0,那么 a 會被排列到 b 之前; 如果 compareFn(a, b) 等于 0,a 和 b 的相對位置不變。要比較數(shù)字而非字符串,比較函數(shù)可以簡單的用 a 減 b,如下的函數(shù)將會將數(shù)組升序排列(如果它不包含 Infinity 和 NaN):
function compareNumbers(a, b) {return a - b; }sort 方法可以使用 函數(shù)表達式 方便地書寫:
const numbers = [4, 2, 5, 1, 3]; numbers.sort(function (a, b) {return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5]// 或者const numbers2 = [4, 2, 5, 1, 3]; numbers2.sort((a, b) => a - b); console.log(numbers2); // [1, 2, 3, 4, 5]a-b -> 升序 b-a -> 降序31. splice() 通過刪除或替換現(xiàn)有元素或者原地添加新的元素來修改數(shù)組。
splice() 方法通過刪除或替換現(xiàn)有元素或者原地添加新的元素來修改數(shù)組,并以數(shù)組形式返回被修改的內(nèi)容。此方法會改變原數(shù)組。
語法:
splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN)
參數(shù):
指定修改的開始位置(從 0 計數(shù))。如果超出了數(shù)組的長度,則從數(shù)組末尾開始添加內(nèi)容;如果是負值,則表示從數(shù)組末位開始的第幾位(從 -1 計數(shù),這意味著 -n 是倒數(shù)第 n 個元素并且等價于 array.length-n);如果負數(shù)的絕對值大于數(shù)組的長度,則表示開始位置為第 0 位。
整數(shù),表示要移除的數(shù)組元素的個數(shù)。如果 deleteCount 大于 start 之后的元素的總數(shù),則從 start 后面的元素都將被刪除(含第 start 位)。如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是說,如果它大于或者等于start之后的所有元素的數(shù)量),那么start之后數(shù)組的所有元素都會被刪除。如果 deleteCount 是 0 或者負數(shù),則不移除元素。這種情況下,至少應添加一個新元素。
要添加進數(shù)組的元素,從start 位置開始。如果不指定,則 splice() 將只刪除數(shù)組元素。
返回值:
由被刪除的元素組成的一個數(shù)組。如果只刪除了一個元素,則返回只包含一個元素的數(shù)組。如果沒有刪除元素,則返回空數(shù)組。
示例:
32. toString() 返回一個字符串,表示指定的數(shù)組及其元素。
toString() 方法返回一個字符串,表示指定的數(shù)組及其元素。
const array1 = [1, 2, 'a', '1a'];console.log(array1.toString()); // expected output: "1,2,a,1a"語法:
toString()返回值: 一個表示數(shù)組所有元素的字符串。33. unshift() 將一個或多個元素添加到數(shù)組的開頭,并返回該數(shù)組的新長度。
const array1 = [1, 2, 3];console.log(array1.unshift(4, 5)); // expected output: 5console.log(array1); // expected output: Array [4, 5, 1, 2, 3]示例:
const arr = [1, 2];arr.unshift(0); // 調(diào)用的結(jié)果是 3,這是新的數(shù)組長度 // arr is [0, 1, 2]arr.unshift(-2, -1); // 新的數(shù)組長度為 5 // arr is [-2, -1, 0, 1, 2]arr.unshift([-4, -3]); // 新的數(shù)組長度為 6 // arr is [[-4, -3], -2, -1, 0, 1, 2]arr.unshift([-7, -6], [-5]); // 新的數(shù)組長度為 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]34. values() 返回一個新的對象,該對象包含數(shù)組每個索引的值。
values() 方法返回一個新的 Array Iterator 對象,該對象包含數(shù)組每個索引的值。
const array1 = ['a', 'b', 'c']; const iterator = array1.values();for (const value of iterator) {console.log(value); }// expected output: "a" // expected output: "b" // expected output: "c"返回值:
一個新的 Array 迭代對象。
示例:
總結(jié)
以上是生活随笔為你收集整理的JS标准内置对象 数组 的 34 个方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 制作PDF文件全攻略
- 下一篇: html中鱼眼效果,视频鱼眼效果制作 视