數組方法
一、數組
-
JavaScript 數組的大小是可調整的,并且可以包含不同 數據類型。(當不需要這些特性時,請使用 類型數組。)
注:JavaScript 類型數組是類似數組的對象,它提供了一種在內存緩沖區中讀取和寫入原始二進制數據的機制。
-
JavaScript 數組不是關聯數組,因此不能使用任意字符串作為索引來訪問數組元素,但必須使用非負整數(或其各自的字符串形式)作為索引來訪問。
二、數組屬性
屬性 | 描述 |
---|---|
constructor | 返回創建數組對象的原型函數。 |
length | 設置或返回數組元素的個數。 |
prototype | 允許你向數組對象添加屬性或方法。 |
1.constructor屬性
var arr = [1,2,3,4]
console.log(arr.constructor);//返回數組的原型函數
2.length屬性
var arr = [1,2,3,4]
console.log(arr.length)//返回數組的長度
3.prototype屬性
// 一個新的數組方法,將數組值轉換為大寫Array.prototype.myUcase = function(){for(i=0;i<arr.length;i++){this[i]=this[i].toUpperCase();}}//創建數組,調用myUcase方法var arr=["apple","mango"]arr.myUcase()console.log(arr)
三、數組方法
1.concat()方法
連接兩個或更多的數組,并返回結果,該方法不會改變現有的數組,而是返回一個新的數組。
語法:
array1.concat(array2, array3,..., arrayX)
示例:
var a = [1,2,3]var b = [4,5,6]var c = a.concat(b)console.log(c) //[1,2,3,4,5,6]
2.copyWhithin()方法
copyWithin() 方法用于從數組的指定位置拷貝元素到數組的另一個指定位置中。
語法:
array.copyWithin(target, start, end)
參數:
trarget
:將序列復制到的從零開始的索引,轉換為整數。這對應于 start
處的元素將被復制到的位置,并且 start
和 end
之間的所有元素都將復制到后續索引。
star
t:從零開始的索引,從該位置開始復制元素,轉換為整數。
end
:結束從 轉換為整數 復制元素的從零開始的索引。copyWithin()
復制直至但不包括 end
。
示例1(不寫結束位置):
var fruits = ["Banana", "Orange", "Apple", "Mango","pink"];fruits.copyWithin(2, 0);console.log(fruits)
示例2(有結束位置):
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];fruits.copyWithin(2, 0, 2);console.log(fruits)
3.entries()方法
entries() 方法返回一個數組的迭代對象,該對象包含數組的鍵值對 (key/value)。
迭代對象中數組的索引值作為 key, 數組元素作為 value。
var fruits = ["Banana", "Orange", "Apple", "Mango"];var a=fruits.entries();console.log(a.next().value)console.log(a.next().value)console.log(a.next().value)console.log(a.next().value)
(1)使用索引和元素進行迭代
const a = ["a", "b", "c"];for (const [index, element] of a.entries()) {console.log(index, element);}
(2)使用for···of循環
const array = ["a", "b", "c"];const arrayEntries = array.entries();for (const element of arrayEntries) {console.log(element);}
(3)對非數組對象調用entries()
entries()
方法讀取 this
的 length
屬性,然后訪問鍵為小于 length
的非負整數的每個屬性。
const arrayLike = {length: 3,0: "a",1: "b",2: "c",3: "d", // ignored by entries() since length is 3};for (const entry of Array.prototype.entries.call(arrayLike)) {console.log(entry);}
4.every()方法
every() 方法用于檢測數組所有元素是否都符合指定條件(通過函數提供)。
every() 方法使用指定函數檢測數組中的所有元素:
- 如果數組中檢測到有一個元素不滿足,則整個表達式返回 false ,且剩余的元素不會再進行檢測。
- 如果所有元素都滿足條件,則返回 true。
語法:
array.every(function(currentValue,index,arr), thisValue)
參數:
參數 | 描述 |
---|---|
currentValue | 必須。當前元素的值 |
index | 可選。當前元素的索引值 |
arr | 可選。當前元素屬于的數組對象 |
thisValue : 可選。對象作為該執行回調時使用,傳遞給函數,用作 “this” 的值。
如果省略了 thisValue ,“this” 的值為 “undefined”
示例:
檢測數組中的數值是否全部大于18,如果是則返回true,如果不是則返回false
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><p>點擊按鈕檢測數組的所有元素是否大于18:</p><button onclick="myFunction()">點我</button><script>var ages = [32,33,16,20]function checkAdult(age){//console.log(age) //age是被檢測的數組元素return age >=18;}function myFunction(){console.log(ages.every(checkAdult))}</script>
</body>
</html>
5.fill()方法
fill() 方法用于將一個固定值替換數組的元素。
語法:
array.fill(value, start, end)
參數:
參數 | 描述 |
---|---|
value | 必需。填充的值。 |
start | 可選。開始填充位置。 |
end | 可選。停止填充位置 (默認為 array.length) |
示例:
var fruits = ["Banana", "Orange", "Apple", "Mango","pink"];
fruits.fill("Runoob", 2, 4);
console.log(fruits);
6.filter()方法
filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
注意: filter() 不會對空數組進行檢測,不會改變原始數組。
語法:
array.filter(function(currentValue,index,arr), thisValue)
參數:
參數 | 描述 |
---|---|
currentValue | 必須。當前元素的值 |
index | 可選。當前元素的索引值 |
arr | 可選。當前元素屬于的數組對象 |
thisValue 可選 | 傳遞給函數的值一般用 “this” 值。 如果這個參數為空, “undefined” 會傳遞給 “this” 值 |
示例:
var arr = [100,100,120,300,230,150]var newArr = arr.filter(function newNum(num){return num<=200;})// var newArr = arr.filter(num=>num<=200) //使用箭頭函數,可以省略returnconsole.log("newArr:"+newArr)console.log("arr"+arr)
輸出結果:
7.find()方法
find() 方法返回符合條件的第一個數組元素。
find() 方法為數組中的每個元素都調用一次函數執行:
- 當數組中的元素在測試條件時返回 true 時, find() 返回符合條件的元素,之后的值不會再調用執行函數。
- 如果沒有符合條件的元素返回 undefined
注意: find() 對于空數組,函數是不會執行的,沒有改變數組的原始值。
注意: IE 11 及更早版本不支持 find() 方法。
語法:
array.find(function(currentValue, index, arr),thisValue)
參數 | 描述 |
---|---|
currentValue | 必需。當前元素 |
index | 可選。當前元素的索引值 |
arr | 可選。當前元素所屬的數組對象 |
More ActionsthisValue | 可選。 傳遞給函數的值一般用 “this” 值。 如果這個參數為空, “undefined” 會傳遞給 “this” 值 |
示例:
//檢測數組當中符合函數小于等于200的元素
var arr = [250,300,100,150,200,150]var newArr = arr.find(function newNum(num){return num<=200;})// var newArr = arr.filter(num=>num<=200) //使用箭頭函數,可以省略returnconsole.log("newArr:"+newArr)console.log("arr"+arr)
運行結果:
8.findIndex()方法
findIndex() 方法返回符合條件的數組第一個元素位置(下標)。
findIndex() 方法為數組中的每個元素都調用一次函數執行:
- 當數組中的元素在測試條件時返回 true 時, findIndex() 返回符合條件的元素的索引位置,之后的值不會再調用執行函數。
- 如果沒有符合條件的元素返回 -1
注意: findIndex() 對于空數組,函數是不會執行的,沒有改變數組的原始值。
語法:
array.findIndex(function(currentValue, index, arr), thisValue)
參數:
參數 | 描述 |
---|---|
currentValue | 必需。當前元素 |
index | 可選。當前元素的索引 |
arr | 可選。當前元素所屬的數組對象 |
thisValue | 可選。 傳遞給函數的值一般用 “this” 值。 如果這個參數為空, “undefined” 會傳遞給 “this” 值 |
示例:
var arr = [250,300,100,150,200,150]var newArr = arr.findIndex(function newNum(num){return num<=200;})// var newArr = arr.filter(num=>num<=200) //使用箭頭函數,可以省略returnconsole.log("newArr:"+newArr)console.log("arr"+arr)
運行結果:
9.forEach()方法
forEach() 方法用于調用數組的每個元素,并將元素傳遞給回調函數。
注意: forEach() 對于空數組是不會執行回調函數的。
語法:
array.forEach(callbackFn(currentValue, index, arr), thisValue)
其他形式的語法格式:
// 箭頭函數
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })// 回調函數
forEach(callbackFn)
forEach(callbackFn, thisArg)// 內聯回調函數
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)
參數:
參數 | 描述 |
---|---|
currentValue | 必需。當前元素 |
index | 可選。當前元素的索引值。 |
arr | 可選。當前元素所屬的數組對象。 |
thisValue | 可選。傳遞給函數的值一般用 “this” 值。 如果這個參數為空, “undefined” 會傳遞給 “this” 值 |
示例:
var sum = 0;var arr = [65, 44, 12, 4];arr.forEach(function fn(item){console.log(`item:${item}`)sum+=item;return sum;})console.log(sum)console.log(arr)
運行結果:
10.from()方法
from() 方法用于通過擁有 length 屬性的對象或可迭代的對象來返回一個數組。
如果對象是數組返回 true,否則返回 false。
語法:sss
Array.from(object, mapFunction, thisValue)
參數:
參數 | 描述 |
---|---|
object | 必需,要轉換為數組的對象。 |
mapFunction | 可選,數組中每個元素要調用的函數。 |
thisValue | 可選,映射函數(mapFunction)中的 this 對象。 |
示例1:
var myArr = Array.from("RUNOOB");
console.log(myArr)
示例2:
返回集合中包含的數組對象
var setObj = new Set(["a", "b", "c"]);var objArr = Array.from(setObj);console.log(`objArr[1]:${objArr[1]}`)
示例3:
使用箭頭語法和映射函數更改元素的值。
var arr = Array.from([1, 2, 3], x => x * 10);console.log(arr) //[10,20,30]
11.includes()方法
includes() 方法用來判斷一個數組是否包含一個指定的值,如果是返回 true,否則false。
語法:
arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
參數:
參數 | 描述 |
---|---|
searchElement | 必須。需要查找的元素值。 |
fromIndex | 可選。從該索引處開始查找 searchElement。如果為負值,則按升序從 array.length + fromIndex 的索引開始搜索。默認為 0。 |
示例:
var arr = ['a', 'b', 'c'];console.log(arr.includes('c', 3)); //false 判斷arr數組當中,下標為3的元素是否為cconsole.log(arr.includes('c', 100)); //false 判斷arr數組當中,下標為100的元素是否為cconsole.log(arr.includes('c')); //true 判斷函數當中是否包含"c"
注意:如果 fromIndex 為負值,計算出的索引將作為開始搜索searchElement的位置。如果計算出的索引小于 0,則整個數組都會被搜索。
var arr = ['a', 'b', 'c'];
console.log(arr.includes('c', -100)); //true
12.indexOf()方法
indexOf() 方法可返回數組中某個指定的元素位置。
該方法將從頭到尾地檢索數組,看它是否含有對應的元素。開始檢索的位置在數組 start 處或數組的開頭(沒有指定 start 參數時)。如果找到一個 item,則返回 item 的第一次出現的位置。開始位置的索引為 0。
如果在數組中沒找到指定元素則返回 -1。
提示如果你想查找字符串最后出現的位置,請使用 lastIndexOf() 方法。
語法:
array.indexOf(item,start)
參數:
參數 | 描述 |
---|---|
item | 必須。查找的元素。 |
start | 可選的整數參數。規定在數組中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字符串的首字符開始檢索。 |
示例:
var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.indexOf("Apple",4);
console.log(`從下標為4的開始檢測,Apple的位置是${a}`) //6
13.isArray()方法
判斷對象是否為數組
語法:
Array.isArray(obj)
參數:
參數 | 描述 |
---|---|
obj | 必需,要判斷的對象。 |
示例:
var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
console.log(Array.isArray(fruits)) // true
14.join()方法
join() 方法用于把數組中的所有元素轉換一個字符串。
元素是通過指定的分隔符進行分隔的。
語法:
array.join(separator)
參數:
參數 | 描述 |
---|---|
separator | 可選。指定要使用的分隔符。如果省略該參數,則使用逗號作為分隔符。 |
示例:
var arr= [2000,2,13,]
var newArr = arr.join("-") //如果不寫參數,那么默認以逗號分隔
console.log(newArr) //2000-2-13
15.keys()方法
keys() 方法用于從數組創建一個包含數組鍵的可迭代對象。
語法:
array.keys()
示例:
var arr= [2000,2,13,]
var newArr = arr.keys()
console.log(newArr) //返回一個數組可迭代對象
16.lastIndexOf()方法
lastIndexOf() 方法可返回一個指定的元素在數組中最后出現的位置,從該字符串的后面向前查找。
如果要檢索的元素沒有出現,則該方法返回 -1。
該方法將從尾到頭地檢索數組中指定元素 item。開始檢索的位置在數組的 start 處或數組的結尾(沒有指定 start 參數時)。如果找到一個 item,則返回 item 從尾向前檢索第一個次出現在數組的位置。數組的索引開始位置是從 0 開始的。
如果在數組中沒找到指定元素則返回 -1。
提示: 如果你想查找數組首次出現的位置,請使用 indexOf() 方法。
語法:
array.lastIndexOf(item,start)
參數:
參數 | 描述 |
---|---|
item | 必需。規定需檢索的字符串值。 |
start | 可選的整數參數。規定在字符串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字符串的最后一個字符處開始檢索。 |
示例:
var arr= [1,2,3,4,5,6,6,5,4,3,2,1]var a = arr.lastIndexOf(2)console.log(a)//10
//從數組中的第四個位置查找字符串2出現的位置:
var arr= [1,2,3,4,5,6,6,5,4,3,2,1]var a = arr.lastIndexOf(2,4)console.log(a)//1
17.map()方法
map() 方法返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值。
map() 方法按照原始數組元素順序依次處理元素。
注意: map() 不會對空數組進行檢測。
注意: map() 不會改變原始數組。
語法:
array.map(function(currentValue,index,arr), thisValue)
參數:
參數 | 描述 |
---|---|
thisValue | 可選。對象作為該執行回調時使用,傳遞給函數,用作 “this” 的值。 如果省略了 thisValue,或者傳入 null、undefined,那么回調函數的 this 為全局對象。 |
currentValue | 必須。當前元素的值 |
index | 可選。當前元素的索引值 |
arr | 可選。當前元素屬于的數組對象 |
示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style></style>
</head>
<body>輸入框:<input type="text" id="ipt" value="10"><script>//將數組中的每個元素乘輸入框指定的值,并且返回var arr = [1,2,3,4]var newArr=arr.map(item=>item*document.getElementById("ipt").value)console.log(newArr)</script>
</body>
</html>
18.pop()方法
pop() 方法用于刪除數組的最后一個元素并返回刪除的元素。
**注意:**此方法改變數組的長度!
提示: 移除數組第一個元素,請使用 shift() 方法。
語法:
array.pop()
示例:
var arr = [1,2,3,4]var a=arr.pop()console.log(a) //返回被刪除的數組元素console.log(arr) //改變數組長度
19.push()方法
push() 方法可向數組的末尾添加一個或多個元素,并返回新的長度。
注意: 新元素將添加在數組的末尾。
注意: 此方法改變數組的長度。
提示: 在數組起始位置添加元素請使用 unshift() 方法。
語法:
array.push(item1, item2, ..., itemX)
參數:
參數 | 描述 |
---|---|
item1, item2, …, itemX | 必需。要添加到數組的元素。 |
示例:
var arr = [1,2,3,4]var a=arr.push(5,5)console.log(a) //返回數組長度 6console.log(arr) //在尾部添加 [1,2,3,4,5,5]
20.unshift()方法
unshift() 方法可向數組的開頭添加一個或更多元素,并返回新的長度。
注意: 該方法將改變數組的數目。
提示: 將新項添加到數組末尾,請使用 push() 方法。
語法:
array.unshift(item1,item2, ..., itemX)
參數:
參數 | 描述 |
---|---|
item1,item2, …, itemX | 可選。向數組起始位置添加一個或者多個元素。 |
示例:
var arr = [1,2,3,4]var a=arr.unshift(5,5)console.log(a) //返回數組長度 6console.log(arr) //在頭部添加 [5,5,1,2,3,4]
21.shift()方法
shift() 方法用于把數組的第一個元素從其中刪除,并返回第一個元素的值。
注意: 此方法改變數組的長度!
提示: 移除數組末尾的元素可以使用 pop() 方法。
語法:
array.shift()
示例:
var arr = [1,2,3,4]var newArr = arr.shift()console.log(newArr) // 被刪除的第一個元素 1console.log(arr) // 刪除第一個元素以后,返回的新的數組 [2,3,4]
22.reduce()方法
reduce() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。
reduce() 可以作為一個高階函數,用于函數的 compose。
注意: reduce() 對于空數組是不會執行回調函數的。
語法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
參數:
參數 | 描述 |
---|---|
total | 必需。初始值, 或者計算結束后的返回值。 |
currentValue | 必需。當前元素 |
currentIndex | 可選。當前元素的索引 |
arr | 可選。當前元素所屬的數組對象。 |
initialValue | 可選。傳遞給函數的初始值 |
示例:
var arr = [1,2,3,4,5]var num = arr.reduce(function getArr(total,item){return total+item;})console.log(num) //15
23.reduceRight()方法
reduceRight() 方法的功能和 reduce() 功能是一樣的,不同的是 reduceRight() 從數組的末尾向前將數組中的數組項做累加。
注意: reduce() 對于空數組是不會執行回調函數的。
語法:
array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
參數:
參數 | 描述 |
---|---|
total | 必需。初始值, 或者計算結束后的返回值。 |
currentValue | 必需。當前元素 |
currentIndex | 可選。當前元素的索引 |
arr | 可選。當前元素所屬的數組對象。 |
initialValue | 可選。傳遞給函數的初始值 |
示例:
var arr = [1,2,3,4,100]var num = arr.reduceRight(function getArr(total,item){console.log(`total:${total}`)console.log(`item:${item}`)return total-item;})console.log(num)
運行結果:
24.reverse()方法
反轉數組的順序
語法:
array.reverse()
示例:
let arr = [1,2,3,4,100]let newArr = arr.reverse() console.log(`newArr:${newArr}`)console.log(`arr:${arr}`)
運行結果:
25.slice()方法
slice() 方法可從已有的數組中返回選定的元素。
slice() 方法可提取字符串的某個部分,并以新的字符串返回被提取的部分。
注意: slice() 方法不會改變原始數組。
語法:
array.slice(start, end)
參數:
參數 | 描述 |
---|---|
start | 可選。規定從何處開始選取。如果該參數為負數,則表示從原數組中的倒數第幾個元素開始提取,slice(-2) 表示提取原數組中的倒數第二個元素到最后一個元素(包含最后一個元素)。 |
end | 可選。規定從何處結束選取。該參數是數組片斷結束處的數組下標。如果沒有指定該參數,那么切分的數組包含從 start 到數組結束的所有元素。如果該參數為負數, 則它表示在原數組中的倒數第幾個元素結束抽取。 slice(-2,-1) 表示抽取了原數組中的倒數第二個元素到最后一個元素(不包含最后一個元素,也就是只有倒數第二個元素)。 |
示例:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];// var myBest = fruits.slice(-3,-1); // 截取從倒數第三個 到 倒數第一個(不包含)的兩個元素 "Lemon", "Apple"var myBest = fruits.slice(-3); // 截取最后三個元素console.log(`myBest:${myBest}`) //"Lemon", "Apple", "Mango"console.log(`fruits:${fruits}`)
26.some()方法
some() 方法用于檢測數組中的元素是否滿足指定條件(函數提供)。
some() 方法會依次執行數組的每個元素:
- 如果有一個元素滿足條件,則表達式返回true , 剩余的元素不會再執行檢測。
- 如果沒有滿足條件的元素,則返回false。
注意: some() 不會對空數組進行檢測。
some() 不會改變原始數組。
語法:
array.some(function(currentValue,index,arr),thisValue)
參數:
參數 | 描述 |
---|---|
currentValue | 必須。當前元素的值 |
index | 可選。當前元素的索引值 |
arr | 可選。當前元素屬于的數組對象 |
thisValue | 可選。對象作為該執行回調時使用,傳遞給函數,用作 “this” 的值。 如果省略了 thisValue ,“this” 的值為 “undefined” |
示例:
let ages = [4, 12, 16, 20]; //聲明一個數組let a= ages.some(function checkAdult(item) {console.log(item)return item >= 18;})console.log(`a:${a}`)
運行結果:
27.sort()方法
sort() 方法用于對數組的元素進行排序。
排序順序可以是字母或數字,并按升序或降序。
默認排序順序為按字母升序。
**注意:**當數字是按字母順序排列時"40"將排在"5"前面,是按數字第一位進行排序,而無關數字的大小。
使用數字排序,必須通過一個函數作為參數來調用。
函數指定數字是按照升序還是降序排列。
注意: 這種方法會改變原始數組!。
語法:
array.sort(sortfunction)
參數:
參數 | 描述 |
---|---|
sortfunction | 可選。規定排序順序。必須是函數。 |
示例1:
//字母排序var arr = ['a','b','c','an','b'];arr.sort(); //升序排列console.log(arr)arr.reverse(); //降序排列就是在升序的基礎上使用反轉數組的方式,來實現降序排列console.log(arr)
示例2:
//數字排序
var arr = [1,2,3,12,1,3,1,12,56,32];arr.sort(); //升序排列console.log(arr)/*arr.reverse(); //降序排列就是在升序的基礎上使用反轉數組的方式,來實現降序排列console.log(arr)*/
思考:那么如何讓數字進行排序呢?
示例3:
//數字排序和降序const arr = [40,100,1,5,25,10];console.log(`arr:${arr}`)let newNum=arr.sort(function(a,b){//console.log(`a:${a} b:${b}`)return b-a //如果是a-b那么就是升序排列});console.log(`newNum:${newNum}`)
28.splice()方法
splice() 方法用于添加或刪除數組中的元素。
**注意:**這種方法會改變原始數組。
語法:
array.splice(index,howmany,item1,.....,itemX)
參數:
參數 | 描述 |
---|---|
index | 必需。規定從何處添加/刪除元素。 該參數是開始插入和(或)刪除的數組元素的下標,必須是數字。 |
howmany | 可選。規定應該刪除多少元素。必須是數字,但可以是 “0”。 如果未規定此參數,則刪除從 index 開始到原數組結尾的所有元素。 |
item1, …, itemX | 可選。要添加到數組的新元素 |
示例:
var arr = [1,2,3,4,5];arr.splice(2,1,100,200); //移除數組的第三個元素,并在數組第三個位置添加新元素100和200,相當于替換。console.log(arr) //[1,2,100,200,4,5]
var arr = [1,2,3,4,5];arr.splice(2,2); //從第三個位置開始刪除數組后的兩個元素3和4console.log(arr) //[1,2,5]
29.toString()方法
將數組轉換為字符串,并返回結果
注意: 數組中的元素之間用逗號分隔。
語法:
array.toString()
示例:
const arr = [1,2,3,4,5];let str=arr.toString(); console.log( str, typeof str) //1,2,3,4,5 string
30.valueOf()方法
valueOf() 方法返回 Array 對象的原始值。
該原始值由 Array 對象派生的所有對象繼承。
valueOf() 方法通常由 JavaScript 在后臺自動調用,并不顯式地出現在代碼中。
注意: valueOf() 方法不會改變原數組。
語法:
array.valueOf()
示例:
const arr = [1,2,3,4,5];let a=arr.valueOf(); console.log( a) //[1,2,3,4,5]
31.of()方法
of() 方法用于將一組值轉換為數組,不考慮參數的數量或類型。
Array.of() 和 Array() 構造函數之間的區別在于對單個參數的處理:Array.of(5) 創建一個具有單個元素 7 的數組,而 Array(5) 創建一個 length 為 5 的空數組。
如果對象是數組返回 true,否則返回 false。
語法:
Array.of(element0)
Array.of(element0, element1)
Array.of(element0, element1, /* … ,*/ elementN)
參數:
參數 | 描述 |
---|---|
element0 | 必需,要轉換為數組的元素。 |
element1, /* … ,*/ elementN | 可選,要轉換為數組的元素。 |
示例:
let a=Array.of(1); // [1]
let b=Array.of(1, 2, 3); // [1, 2, 3]
let c=Array.of(undefined); // [undefined]
console.log(a)
console.log(b)
console.log(c)
Array.of()與Array()的區別:
let a1=Array.of(7); // [7] 7個undefined組成的數組let a2=Array(7); // array of 7 empty slots 7個空槽let b1=Array.of(1, 2, 3); // [1, 2, 3]let b2=Array(1, 2, 3); // [1, 2, 3]console.log(`a1使用Array.of()創建的:`,a1)console.log(`a2b1使用Array()創建的:`,a2)console.log(`b1使用Array.of()創建的:`,b1)console.log(`b2使用Array()創建的:`,b2)
運行結果:
32.at()方法
at() 方法用于接收一個整數值并返回該索引對應的元素,允許正數和負數。負整數從數組中的最后一個元素開始倒數。
匹配給定索引的數組中的元素。如果找不到指定的索引,則返回 undefined。
在傳遞非負數時,at() 方法等價于括號表示法。例如,array[0] 和 array.at(0) 均返回第一個元素。但是,當你需要從數組的末端開始倒數時,則不能使用 Python 和 R 語言中支持的 array[-1],因為方括號內的所有值都會被視為字符串屬性,因此你最終讀取的是 array[“-1”],這只是一個普通的字符串屬性而不是數組索引。
通常的做法是訪問 length 并將其減去從末端開始的相對索引。例如,array[array.length - 1]。at() 方法允許使用相對索引,因此上面的示例可以簡化為 array.at(-1)。更正式地,當 index < 0 時,該方法將訪問索引 index + array.length。
at() 方法是通用的。其僅期望 this 具有 length 屬性和以整數為鍵的屬性。
語法:
at(index)
參數:
參數 | 描述 |
---|---|
index | 要返回的數組元素的索引(位置)。當傳遞負數時,支持從數組末端開始的相對索引;也就是說,如果使用負數,返回的元素將從數組的末端開始倒數。 |
示例:
const array1 = [5, 12, 8, 130, 44];let index1 = 2;str1 = `索引號為 ${index1} 的值為 ${array1.at(index1)}`;console.log(str1);let index2 = -2;str2 = `索引號為 ${index2} 的值為 ${array1.at(index2)}`;console.log(str2)
運行結果:
33.flat()方法
flat() 方法方法會按照一個可指定的深度遞歸遍歷數組,并將所有元素與遍歷到的子數組中的元素合并為一個新數組返回,可以實現數組扁平化(數組降維)。
flat() 方法返回一個包含將數組與子數組中所有元素的新數組。
flat() 方法會遞歸地遍歷數組,將所有嵌套的數組元素提取出來,生成一個新的一維數組。
語法:
flat()
flat(depth)
參數:
參數 | 描述 |
---|---|
depth | 指定要提取嵌套數組的結構深度,默認值為 1。 |
示例:
let arr1 = [1, 2, [3, 4, [5, 6]]];let newArr = arr1.flat();console.log(newArr);// 輸出: [1, 2, 3, 4, [5, 6]]// 指定深度為2let arr2 = [1, 2, [3, 4, [5, 6]]];let arr3 = arr2.flat(2);console.log(arr3);// 輸出: [1, 2, 3, 4, 5, 6]//使用 Infinity,可展開任意深度的嵌套數組let arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];let arr5=arr4.flat(Infinity);// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]console.log(arr5)
運行結果:
34.flatMap()方法
首先將數組中的每一個元素都執行方法的回調函數,然后將結果返回到 flatMap 這個方法中然后將其展平,最終輸出
flatMap() 方法首先使用映射函數映射每個元素,然后將結果壓縮成一個新數組。它與 map 連著深度值為 1 的 flat 幾乎相同,但 flatMap 通常在合并成一種方法的效率稍微高一些。
flatMap() 方法一個新的數組,其中每個元素都是回調函數的結果,并且結構深度 depth 值為 1。
語法:
// 箭頭函數
flatMap((currentValue) => { /* … */ } )
flatMap((currentValue, index) => { /* … */ } )
flatMap((currentValue, index, array) => { /* … */ } )// 回調函數
flatMap(callbackFn)
flatMap(callbackFn, thisArg)// 行內回調函數
flatMap(function(currentValue) { /* … */ })
flatMap(function(currentValue, index) { /* … */ })
flatMap(function(currentValue, index, array){ /* … */ })
flatMap(function(currentValue, index, array) { /* … */ }, thisArg)
參數:
參數 | 描述 |
---|---|
callback | 可以生成一個新數組中的元素的函數,可以傳入三個參數:currentValue 當前正在數組中處理的元素index 可選可選的。數組中正在處理的當前元素的索引。array 可選可選的。被調用的 map 數組 |
thisArg | 可選的。執行 callback 函數時 使用的this 值。 |
示例:
const arr1 = [1, 2, 1];const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));
//注意只能展開一層
console.log(result);// Array [1, 2, 2, 1]
35.with()方法
with() 方法用于更新指定的數組元素。
with() 方法會返回一個新數組。
with() 方法不會改變原始數組。
語法:
array.with(index, value)
參數:
參數 | 描述 |
---|---|
index | 必需。要更改的元素的索引(位置)。負索引從數組末尾開始計數。 |
value | 必需。新的值。 |
示例:
const arr = [1,2,3,4];const arr1 = arr.with(1, 100);console.log(arr1) //[1,100,3,4]
36.findLastIndex()方法
findLastIndex() 方法會對數組中的每個元素執行一個函數。
findLastIndex() 方法返回通過測試的最后一個元素的索引(位置)。
如果沒有找到匹配項,則返回 -1。
對于空數組元素,findLastIndex() 方法不會執行函數。
findLastIndex() 方法不會改變原始數組。
語法:
array.findLastIndex(function(currentValue, index, arr), thisValue)
參數:
參數 | 描述 |
---|---|
function | 必需。為每個數組元素運行的函數。 |
currentValue | 必需。當前元素的值。 |
index | 可選。當前元素的索引。 |
arr | 可選。當前元素所在的數組。 |
thisValue | 可選,默認為 undefined。作為函數的 this 值傳遞。 |
示例:
const ages = [3, 30, 18, 20];let a = ages.findLastIndex(age => age>18);console.log(`最后一個大于18的元素的下標為:${a}`) //3
37.lastIndexOf()方法
檢查數組當中符合條件的元素最后一次出現的下標,從該字符串的后面向前查找,如果要檢索的元素沒有出現,則該方法返回 -1。
語法:
array.lastIndexOf(item,start)
參數:
參數 | 描述 |
---|---|
item | 必需。規定需檢索的字符串值。 |
start | 可選的整數參數。規定在字符串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字符串的最后一個字符處開始檢索。 |
示例:
const arr = [3, 30, 18, 20];let a = arr.lastIndexOf(20);console.log(`元素20最后一次出現的的下標為:${a}`) //3
const arr = [3, 30, 18, 20];let a = arr.lastIndexOf(40);console.log(`元素40最后一次出現的的下標為:${a}`) //-1
const arr = [3, 20, 18, 20];let a = arr.lastIndexOf(20,2);console.log(`元素20從下標2開始向后,最后一次出現的的下標為:${a}`) //1
38.findLast()方法
findLast() 方法返回通過條件判斷的最后一個元素的值。
findLast() 方法會對數組中的每個元素執行一個函數。
如果未找到符合條件的元素,則 findLast() 方法返回 undefined。
對于空數組元素,findLast() 方法不會執行函數。
findLast() 方法不會改變原始數組。
語法:
array.findLast(function(currentValue, index, arr), thisValue)
參數:
方法 | 描述 |
---|---|
indexOf() | 找到具有指定值的第一個元素的索引 |
lastIndexOf() | 找到具有指定值的最后一個元素的索引 |
find() | 找到通過測試的第一個元素的值 |
findIndex() | 找到通過測試的第一個元素的索引 |
findLast() | 找到通過測試的最后一個元素的值 |
findLastIndex() | 找到通過測試的最后一個元素的索引 |
示例:
const ages = [3, 10, 18, 20,30,40];let a = ages.findLast(age => age>18) console.log(`最后一次符合大于18的條件的元素是${a}`) //40
39.toReversed()方法
反轉數組順序,與reverse()方法實現的效果相同,是reverse()方法的復制版本。
語法:
array.toReversed()
示例:
// 創建數組const arr = [1,2,3,4];// 反轉數組const arr1 = arr.toReversed();console.log(arr1)//[4,3,2,1]
與reverse 的區別
toReversed()
的返回值永遠不是稀疏的。空槽在返回的數組中變為 undefined
。
// 創建數組const arr = [1,,2,3,4];// 反轉數組const arr1 = arr.toReversed();console.log(arr1)
// 創建數組const arr = [1,,2,3,4];// 反轉數組const arr1 = arr.reverse();console.log(arr1)
40.toSorted() 方法
toSorted() 方法用于對數組中的元素按字母順序進行排序,排序的方法與sort()方法一致,同樣的toSorted()的返回值永遠不是稀疏的。空槽在返回的數組中變為 undefined
。
toSorted() 方法返回一個新的數組。
toSorted() 方法不會修改原始數組。
toSorted() 是 sort() 方法的復制版本。
語法:
array.toSorted(compareFunction)
參數:
參數 | 描述 |
---|---|
compareFunction(可選) | 定義排序順序的函數。該函數應根據參數返回負值、零或正值,例如:function(a, b) { return a - b; } 當 sort() 比較兩個值時,它會將值傳遞給比較函數,并根據返回值(負值、零、正值)對值進行排序。 |
示例:
//降序排序
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruits2 = fruits.toSorted();
fruits2.reverse();
這里數字的排序與sort()方法一致
//查找最小值
const points = [40, 100, 1, 5, 25, 10];let points2 = points.toSorted(function(a, b) { return a - b; });let lowest = points2[0];console.log(lowest) //1
//查找最大值
const points = [40, 100, 1, 5, 25, 10];let points2 = points.toSorted(function(a, b) { return b - a; });let highest = points2[0];console.log(highest)
41.toSpliced() 方法
toSpliced() 方法用于向數組中添加和/或移除元素,toSpliced()的返回值永遠不是稀疏的。空槽在返回的數組中變為 undefined
。
toSpliced() 方法返回一個新的數組。
toSpliced() 方法不會修改原始數組。
toSpliced() 是 splice() 方法的復制版本。
語法:
array.toSpliced(index, count, item1, ..., itemX)
參數:
參數 | 描述 |
---|---|
index(必需) | 要添加或移除元素的索引(位置)。負值從數組末尾開始計數。 |
count(可選) | 要移除的元素數量。 |
item1, …(可選) | 要添加的新元素。 |
示例:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruits2 = fruits.toSpliced(2, 2);
console.log(fruits2 )// ["Banana", "Orange"]