前端JavaScript數(shù)組方法總結(jié)(非常詳細(xì)!)
一、主要的數(shù)組方法:
join()
:用指定的分隔符將數(shù)組每一項(xiàng)拼接為字符串push()
:向數(shù)組的末尾添加新元素pop()
:刪除數(shù)組的最后一項(xiàng)shift()
:刪除數(shù)組的第一項(xiàng)unshift()
:向數(shù)組首位添加新元素slice()
:按照條件查找出其中的部分元素splice()
:對(duì)數(shù)組進(jìn)行增刪改fill()
: 方法能使用特定值填充數(shù)組中的一個(gè)或多個(gè)元素filter()
:“過濾”功能concat()
:用于連接兩個(gè)或多個(gè)數(shù)組indexOf()
:檢測(cè)當(dāng)前值在數(shù)組中第一次出現(xiàn)的位置索引lastIndexOf()
:檢測(cè)當(dāng)前值在數(shù)組中最后一次出現(xiàn)的位置索引every()
:判斷數(shù)組中每一項(xiàng)都是否滿足條件some()
:判斷數(shù)組中是否存在滿足條件的項(xiàng)includes()
:判斷一個(gè)數(shù)組是否包含一個(gè)指定的值sort()
:對(duì)數(shù)組的元素進(jìn)行排序reverse()
:對(duì)數(shù)組進(jìn)行倒序forEach()
:ES5 及以下循環(huán)遍歷數(shù)組每一項(xiàng)map()
:ES6 循環(huán)遍歷數(shù)組每一項(xiàng)copyWithin()
:用于從數(shù)組的指定位置拷貝元素到數(shù)組的另一個(gè)指定位置中find()
:返回匹配的值findIndex()
:返回匹配位置的索引toLocaleString()、toString()
:將數(shù)組轉(zhuǎn)換為字符串flat()、flatMap()
:扁平化數(shù)組entries() 、keys() 、values()
:遍歷數(shù)組
二、各類方法的具體使用
1.join()
在 JavaScript 里,join()
是數(shù)組對(duì)象的一個(gè)方法,其作用是把數(shù)組里的所有元素連接成一個(gè)字符串。你可以指定一個(gè)分隔符,該分隔符會(huì)被 插入到數(shù)組元素之間。若不指定分隔符,默認(rèn)會(huì)使用逗號(hào) ‘,’。
語法:
arr.join([separator])
arr
:需要連接元素的數(shù)組。separator
(可選):用于分隔數(shù)組元素的字符串。若省略該參數(shù),數(shù)組元素會(huì)用逗號(hào)分隔。
示例:
//示例 1:使用默認(rèn)分隔符 const fruits = ['Apple', 'Banana', 'Cherry']; const result = fruits.join(); console.log(result); //Apple,Banana,Cherry //示例 2:指定分隔符 const numbers = [1, 2, 3, 4, 5]; const customResult = numbers.join('-'); console.log(customResult); //1-2-3-4-5 //示例 3:使用空字符串作為分隔符 const letters = ['H', 'e', 'l', 'l', 'o']; const noSeparatorResult = letters.join(''); console.log(noSeparatorResult); //Hello
2.push()
在 JavaScript 中,push()
是數(shù)組對(duì)象的一個(gè)方法,其主要作用是在數(shù)組的末尾添加一個(gè)或多個(gè)元素,并返回新數(shù)組的長度。該方法會(huì)直接修改原數(shù)組。
語法:
arr.push(element1[, ...[, elementN]])
arr
:要操作的數(shù)組。element1, ..., elementN
:要添加到數(shù)組末尾的一個(gè)或多個(gè)元素。
示例:
// 示例 1:添加單個(gè)元素 const animals = ['dog', 'cat']; const newLength = animals.push('rabbit'); console.log('新數(shù)組長度:', newLength); console.log('更新后的數(shù)組:', animals); //新數(shù)組長度: 3 //更新后的數(shù)組: ['dog', 'cat', 'rabbit'] // 示例 2:添加多個(gè)元素 const numbers = [1, 2, 3]; const updatedLength = numbers.push(4, 5); console.log('新數(shù)組長度:', updatedLength); console.log('更新后的數(shù)組:', numbers); //新數(shù)組長度: 5 //更新后的數(shù)組: [1, 2, 3, 4, 5]
3.pop()
在 JavaScript 里,pop()
是數(shù)組對(duì)象的一個(gè)方法。其作用是移除數(shù)組的最后一個(gè)元素,并且返回該被移除的元素。若數(shù)組為空,pop()
方法不會(huì)報(bào)錯(cuò),而是返回 undefined
,同時(shí)此方法會(huì)直接對(duì)原數(shù)組進(jìn)行修改。
語法:
arr.pop()
arr
:需要操作的數(shù)組。
示例:
// 示例 1:對(duì)非空數(shù)組使用 pop() 方法 const fruits = ['apple', 'banana', 'cherry']; const removedFruit = fruits.pop(); console.log('被移除的元素:', removedFruit); console.log('更新后的數(shù)組:', fruits); //被移除的元素: cherry //更新后的數(shù)組: ['apple', 'banana'] // 示例 2:對(duì)空數(shù)組使用 pop() 方法 const emptyArray = []; const result = emptyArray.pop(); console.log('返回值:', result); console.log('數(shù)組狀態(tài):', emptyArray); //返回值: undefined //數(shù)組狀態(tài): []
4.shift()
在 JavaScript 中,shift()
是數(shù)組對(duì)象的一個(gè)方法,其主要功能是移除數(shù)組的第一個(gè)元素,并返回該被移除的元素。如果數(shù)組為空,shift()
方法會(huì)返回 undefined
,同時(shí)該方法會(huì)直接修改原數(shù)組。
語法:
arr.shift()
arr
:要操作的數(shù)組。
示例:
// 示例 1:對(duì)非空數(shù)組使用 shift() 方法 const colors = ['red', 'green', 'blue']; const removedColor = colors.shift(); console.log('被移除的元素:', removedColor); console.log('更新后的數(shù)組:', colors); //被移除的元素: red //更新后的數(shù)組: ['green', 'blue'] // 示例 2:對(duì)空數(shù)組使用 shift() 方法 const emptyArr = []; const result = emptyArr.shift(); console.log('返回值:', result); console.log('數(shù)組狀態(tài):', emptyArr); //返回值: undefined //數(shù)組狀態(tài): []
5.unshift()
在 JavaScript 中,unshift()
是數(shù)組對(duì)象的一個(gè)方法,其作用是在數(shù)組的開頭添加一個(gè)或多個(gè)元素,并返回新數(shù)組的長度。該方法會(huì)直接修改原數(shù)組。
語法:
arr.unshift(element1[, ...[, elementN]])
arr
:要操作的數(shù)組。element1, ..., elementN
:要添加到數(shù)組開頭的一個(gè)或多個(gè)元素。
示例:
// 示例 1:添加單個(gè)元素 const numbers = [2, 3, 4]; const newLength = numbers.unshift(1); console.log('新數(shù)組的長度:', newLength); console.log('更新后的數(shù)組:', numbers); //新數(shù)組的長度: 4 //更新后的數(shù)組: [1, 2, 3, 4] // 示例 2:添加多個(gè)元素 const fruits = ['banana', 'cherry']; const updatedLength = fruits.unshift('apple', 'grape'); console.log('新數(shù)組的長度:', updatedLength); console.log('更新后的數(shù)組:', fruits); //新數(shù)組的長度: 4 //更新后的數(shù)組: ['apple', 'grape', 'banana', 'cherry']
6.slice()
在 JavaScript 中,slice()
是數(shù)組對(duì)象的一個(gè)方法,用于從原數(shù)組中提取出一部分元素,組成一個(gè)新的數(shù)組,而不會(huì)對(duì)原數(shù)組進(jìn)行修改。
語法:
arr.slice([begin[, end]])
arr
:需要操作的數(shù)組。begin
(可選):提取元素的起始索引位置。如果省略該參數(shù),默認(rèn)從索引 0 開始。若為負(fù)數(shù),則表示從數(shù)組末尾開始倒數(shù)的位置,例如-1
表示最后一個(gè)元素。end
(可選):提取元素的結(jié)束索引位置(不包含該索引對(duì)應(yīng)的元素)。如果省略該參數(shù),會(huì)提取從begin
到數(shù)組末尾的所有元素。若為負(fù)數(shù),則表示從數(shù)組末尾開始倒數(shù)的位置。
示例:
// 示例 1:省略參數(shù) const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']; const newFruits = fruits.slice(); console.log('原數(shù)組:', fruits); console.log('新數(shù)組:', newFruits); //原數(shù)組: ['apple', 'banana', 'cherry', 'date', 'elderberry'] //新數(shù)組: ['apple', 'banana', 'cherry', 'date', 'elderberry'] // 示例 2:指定 begin 參數(shù) const numbers = [1, 2, 3, 4, 5]; const newNumbers = numbers.slice(2); console.log('原數(shù)組:', numbers); console.log('新數(shù)組:', newNumbers); //原數(shù)組: [1, 2, 3, 4, 5] //新數(shù)組: [3, 4, 5] // 示例 3:指定 begin 和 end 參數(shù) const animals = ['cat', 'dog', 'elephant', 'fox', 'giraffe']; const newAnimals = animals.slice(1, 3); console.log('原數(shù)組:', animals); console.log('新數(shù)組:', newAnimals); //原數(shù)組: ['cat', 'dog', 'elephant', 'fox', 'giraffe'] //新數(shù)組: ['dog', 'elephant'] // 示例 4:使用負(fù)索引 const colors = ['red', 'green', 'blue', 'yellow', 'purple']; const newColors = colors.slice(-3, -1); console.log('原數(shù)組:', colors); console.log('新數(shù)組:', newColors); //原數(shù)組: ['red', 'green', 'blue', 'yellow', 'purple'] //新數(shù)組: ['blue', 'yellow']
7.fill()
在 JavaScript 中,fill()
是數(shù)組對(duì)象的一個(gè)方法,它可以用一個(gè)固定值填充數(shù)組中的一個(gè)或多個(gè)元素。該方法會(huì)直接修改原數(shù)組,并返回修改后的數(shù)組。
語法:
arr.fill(value[, start[, end]])
arr
:要操作的數(shù)組。value
:用來填充數(shù)組元素的值。start
(可選):開始填充的索引位置,默認(rèn)為 0。如果是負(fù)數(shù),則表示從數(shù)組末尾開始倒數(shù)的位置。end
(可選):結(jié)束填充的索引位置(不包含該索引對(duì)應(yīng)的元素),默認(rèn)為數(shù)組的長度。如果是負(fù)數(shù),則表示從數(shù)組末尾開始倒數(shù)的位置。
示例:
// 示例 1:用一個(gè)值填充整個(gè)數(shù)組 const numbers = [1, 2, 3, 4, 5]; const filledNumbers = numbers.fill(0); console.log('原數(shù)組(已被修改):', numbers); console.log('填充后返回的數(shù)組:', filledNumbers); //原數(shù)組(已被修改): [0, 0, 0, 0, 0] //填充后返回的數(shù)組: [0, 0, 0, 0, 0] // 示例 2:指定開始和結(jié)束位置進(jìn)行填充 const letters = ['a', 'b', 'c', 'd', 'e']; const filledLetters = letters.fill('x', 1, 3); console.log('原數(shù)組(已被修改):', letters); console.log('填充后返回的數(shù)組:', filledLetters); //原數(shù)組(已被修改): ['a', 'x', 'x', 'd', 'e'] //填充后返回的數(shù)組: ['a', 'x', 'x', 'd', 'e'] // 示例 3:使用負(fù)索引進(jìn)行填充 const colors = ['red', 'green', 'blue', 'yellow', 'purple']; const filledColors = colors.fill('orange', -2); console.log('原數(shù)組(已被修改):', colors); console.log('填充后返回的數(shù)組:', filledColors); //原數(shù)組(已被修改): ['red', 'green', 'blue', 'orange', 'orange'] //填充后返回的數(shù)組: ['red', 'green', 'blue', 'orange', 'orange']
8.filter()
在 JavaScript 中,filter()
是數(shù)組對(duì)象的一個(gè)方法,其主要作用是創(chuàng)建一個(gè)新數(shù)組,新數(shù)組中的元素是原數(shù)組中滿足指定條件的所有元素。filter()
方法不會(huì)改變?cè)瓟?shù)組,而是返回一個(gè)新數(shù)組。
語法:
arr.filter(callback(element[, index[, array]])[, thisArg])
arr
:要操作的數(shù)組。callback
:用來測(cè)試數(shù)組每個(gè)元素的函數(shù),它接收三個(gè)參數(shù):element
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用filter()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值
示例:
// 示例 1:篩選出數(shù)組中的偶數(shù) const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(function (number) { return number % 2 === 0; }); console.log('原數(shù)組:', numbers); console.log('篩選出的偶數(shù)數(shù)組:', evenNumbers); //原數(shù)組: [1, 2, 3, 4, 5, 6] //篩選出的偶數(shù)數(shù)組: [2, 4, 6] // 示例 2:使用箭頭函數(shù)和索引篩選元素 const words = ['apple', 'banana', 'cherry', 'date']; const longWords = words.filter((word, index) => { return word.length > 5 && index % 2 === 0; }); console.log('原數(shù)組:', words); console.log('篩選出的長單詞且索引為偶數(shù)的數(shù)組:', longWords); //原數(shù)組: ['apple', 'banana', 'cherry', 'date'] //篩選出的長單詞且索引為偶數(shù)的數(shù)組: ['cherry'] // 示例 3:篩選出對(duì)象數(shù)組中滿足條件的對(duì)象 const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ]; const adults = users.filter(user => user.age >= 25); console.log('原數(shù)組:', users); console.log('篩選出的成年人數(shù)組:', adults); //原數(shù)組: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ] //篩選出的成年人數(shù)組: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]
9.concat()
在 JavaScript 里,concat()
是數(shù)組對(duì)象的一個(gè)方法,其用途是把兩個(gè)或多個(gè)數(shù)組連接起來,形成一個(gè)新的數(shù)組。此方法不會(huì)改變?cè)瓟?shù)組,而是返回一個(gè)全新的數(shù)組,該數(shù)組包含了原數(shù)組以及被連接數(shù)組的所有元素。
語法:
const newArray = oldArray.concat(value1[, value2[, ...[, valueN]]])
oldArray
:調(diào)用concat()
方法的原始數(shù)組。value1, value2, ..., valueN
(可選):要連接到oldArray
末尾的數(shù)組或值。如果這些參數(shù)是數(shù)組,它們的元素會(huì)被逐個(gè)添加到新數(shù)組中;如果是其他值,則直接添加到新數(shù)組末尾。
示例:
// 示例 1:連接兩個(gè)數(shù)組 const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const newArray = array1.concat(array2); console.log('原數(shù)組1:', array1); console.log('原數(shù)組2:', array2); console.log('連接后的新數(shù)組:', newArray); //原數(shù)組1: [1, 2, 3] //原數(shù)組2: [4, 5, 6] //連接后的新數(shù)組: [1, 2, 3, 4, 5, 6] // 示例 2:連接多個(gè)數(shù)組 const firstArray = ['a', 'b']; const secondArray = ['c', 'd']; const thirdArray = ['e', 'f']; const combinedArray = firstArray.concat(secondArray, thirdArray); console.log('原數(shù)組1:', firstArray); console.log('原數(shù)組2:', secondArray); console.log('原數(shù)組3:', thirdArray); console.log('連接后的新數(shù)組:', combinedArray); //原數(shù)組1: ['a', 'b'] //原數(shù)組2: ['c', 'd'] //原數(shù)組3: ['e', 'f'] //連接后的新數(shù)組: ['a', 'b', 'c', 'd', 'e', 'f'] // 示例 3:連接數(shù)組和值 const originalArray = [10, 20]; const newArrayWithValue = originalArray.concat(30, [40, 50]); console.log('原數(shù)組:', originalArray); console.log('連接后的新數(shù)組:', newArrayWithValue); //原數(shù)組: [10, 20] //連接后的新數(shù)組: [10, 20, 30, 40, 50]
10.indexOf()
在 JavaScript 中,indexOf()
是數(shù)組對(duì)象的一個(gè)方法,用于查找某個(gè)指定的值在數(shù)組中首次出現(xiàn)的索引位置。如果該值存在于數(shù)組中,就返回它的索引;若不存在,則返回 -1
。此方法進(jìn)行的是嚴(yán)格相等比較(即 ===
)。
語法:
arr.indexOf(searchElement[, fromIndex])
arr
:要進(jìn)行查找操作的數(shù)組。searchElement
:需要在數(shù)組中查找的元素。fromIndex
(可選):開始查找的索引位置,默認(rèn)值為0
。若該值為負(fù)數(shù),則從數(shù)組末尾倒數(shù)相應(yīng)位置開始查找,但查找順序依然是從前往后。
示例:
// 示例 1:基本查找 const fruits = ['apple', 'banana', 'cherry', 'banana']; const index = fruits.indexOf('banana'); console.log('數(shù)組:', fruits); console.log('"banana" 首次出現(xiàn)的索引:', index); //數(shù)組: ['apple', 'banana', 'cherry', 'banana'] //"banana" 首次出現(xiàn)的索引: 1 // 示例 2:指定起始索引查找 const numbers = [10, 20, 30, 20, 40]; const newIndex = numbers.indexOf(20, 2); console.log('數(shù)組:', numbers); console.log('從索引 2 開始查找,"20" 首次出現(xiàn)的索引:', newIndex); //數(shù)組: [10, 20, 30, 20, 40] //從索引 2 開始查找,"20" 首次出現(xiàn)的索引: 3 // 示例 3:查找不存在的元素 const colors = ['red', 'green', 'blue']; const nonExistentIndex = colors.indexOf('yellow'); console.log('數(shù)組:', colors); console.log('"yellow" 首次出現(xiàn)的索引:', nonExistentIndex); //數(shù)組: ['red', 'green', 'blue'] //"yellow" 首次出現(xiàn)的索引: -1
11.lastIndexOf()
在 JavaScript 中,lastIndexOf()
是數(shù)組對(duì)象的一個(gè)方法,其主要作用是查找指定元素在數(shù)組中最后一次出現(xiàn)的索引位置。如果數(shù)組中存在該元素,就返回其最后一次出現(xiàn)的索引;若不存在,則返回 -1
。該方法進(jìn)行的是嚴(yán)格相等比較(即 ===
)。
語法:
arr.lastIndexOf(searchElement[, fromIndex])
arr
:要進(jìn)行查找操作的數(shù)組。searchElement
:需要在數(shù)組中查找的元素。fromIndex
(可選):開始反向查找的索引位置。默認(rèn)值為數(shù)組的長度減 1,也就是從數(shù)組的最后一個(gè)元素開始查找。若該值為負(fù)數(shù),則從數(shù)組末尾倒數(shù)相應(yīng)位置開始反向查找。
示例:
// 示例 1:基本查找 const fruits = ['apple', 'banana', 'cherry', 'banana']; const lastIndex = fruits.lastIndexOf('banana'); console.log('數(shù)組:', fruits); console.log('"banana" 最后一次出現(xiàn)的索引:', lastIndex); //數(shù)組: ['apple', 'banana', 'cherry', 'banana'] //"banana" 最后一次出現(xiàn)的索引: 3 // 示例 2:指定起始索引查找 const numbers = [10, 20, 30, 20, 40]; const newLastIndex = numbers.lastIndexOf(20, 2); console.log('數(shù)組:', numbers); console.log('從索引 2 開始反向查找,"20" 最后一次出現(xiàn)的索引:', newLastIndex); //數(shù)組: [10, 20, 30, 20, 40] //從索引 2 開始反向查找,"20" 最后一次出現(xiàn)的索引: 1 // 示例 3:查找不存在的元素 const colors = ['red', 'green', 'blue']; const nonExistentLastIndex = colors.lastIndexOf('yellow'); console.log('數(shù)組:', colors); console.log('"yellow" 最后一次出現(xiàn)的索引:', nonExistentLastIndex); //數(shù)組: ['red', 'green', 'blue'] //"yellow" 最后一次出現(xiàn)的索引: -1
12.every()
在 JavaScript 里,every()
是數(shù)組對(duì)象的一個(gè)方法。它用于檢測(cè)數(shù)組里的所有元素是否都滿足指定的條件。該方法會(huì)對(duì)數(shù)組中的每個(gè)元素執(zhí)行一次提供的測(cè)試函數(shù),若所有元素都使測(cè)試函數(shù)返回 true
,則 every()
方法返回 true
;只要有一個(gè)元素使測(cè)試函數(shù)返回 false
,就會(huì)立即停止遍歷并返回 false
。此方法不會(huì)改變?cè)瓟?shù)組。
語法:
arr.every(callback(element[, index[, array]])[, thisArg])
arr
:要進(jìn)行檢測(cè)的數(shù)組。callback
:用來測(cè)試每個(gè)元素的函數(shù),它接收三個(gè)參數(shù):element
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用every()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值。
示例:
// 示例 1:檢查數(shù)組中的所有元素是否都大于 0 const numbers = [1, 2, 3, 4, 5]; const allPositive = numbers.every(function (number) { return number > 0; }); console.log('數(shù)組:', numbers); console.log('數(shù)組中的所有元素是否都大于 0:', allPositive); //數(shù)組: [1, 2, 3, 4, 5] //數(shù)組中的所有元素是否都大于 0: true // 示例 2:使用箭頭函數(shù)檢查數(shù)組中的所有元素長度是否都大于 3 const words = ['apple', 'banana', 'cherry']; const allLongWords = words.every(word => word.length > 3); console.log('數(shù)組:', words); console.log('數(shù)組中的所有元素長度是否都大于 3:', allLongWords); //數(shù)組: ['apple', 'banana', 'cherry'] //數(shù)組中的所有元素長度是否都大于 3: true // 示例 3:檢查數(shù)組中的所有元素是否都是偶數(shù) const mixedNumbers = [2, 4, 6, 7]; const allEven = mixedNumbers.every(num => num % 2 === 0); console.log('數(shù)組:', mixedNumbers); console.log('數(shù)組中的所有元素是否都是偶數(shù):', allEven); //數(shù)組: [2, 4, 6, 7] //數(shù)組中的所有元素是否都是偶數(shù): false
13.some()
在 JavaScript 中,some()
是數(shù)組對(duì)象的一個(gè)方法,用于檢測(cè)數(shù)組中是否至少有一個(gè)元素滿足指定的條件。它會(huì)對(duì)數(shù)組中的每個(gè)元素依次執(zhí)行你提供的測(cè)試函數(shù),只要有一個(gè)元素使測(cè)試函數(shù)返回 true
,some()
方法就會(huì)立即返回 true
;若所有元素都使測(cè)試函數(shù)返回 false
,則 some()
方法返回 false
。此方法不會(huì)改變?cè)瓟?shù)組。
語法:
arr.some(callback(element[, index[, array]])[, thisArg])
arr
:要進(jìn)行檢測(cè)的數(shù)組。callback
:用于測(cè)試每個(gè)元素的函數(shù),該函數(shù)接收三個(gè)參數(shù):element
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用some()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值。
示例:
// 示例 1:檢查數(shù)組中是否有元素大于 5 const numbers = [1, 3, 7, 4]; const hasGreaterThanFive = numbers.some(function (number) { return number > 5; }); console.log('數(shù)組:', numbers); console.log('數(shù)組中是否有元素大于 5:', hasGreaterThanFive); //數(shù)組: [1, 3, 7, 4] //數(shù)組中是否有元素大于 5: true // 示例 2:使用箭頭函數(shù)檢查數(shù)組中是否有元素長度小于 3 const words = ['apple', 'cat', 'banana']; const hasShortWord = words.some(word => word.length < 3); console.log('數(shù)組:', words); console.log('數(shù)組中是否有元素長度小于 3:', hasShortWord); //數(shù)組: ['apple', 'cat', 'banana'] //數(shù)組中是否有元素長度小于 3: false // 示例 3:檢查數(shù)組中是否有偶數(shù) const mixedNumbers = [1, 3, 5, 8]; const hasEvenNumber = mixedNumbers.some(num => num % 2 === 0); console.log('數(shù)組:', mixedNumbers); console.log('數(shù)組中是否有偶數(shù):', hasEvenNumber); //數(shù)組: [1, 3, 5, 8] //數(shù)組中是否有偶數(shù): true
14.includes()
在 JavaScript 里,includes()
是數(shù)組對(duì)象的一個(gè)方法,它用于判斷數(shù)組是否包含某個(gè)指定的值。若包含則返回 true
,不包含則返回 false
。此方法進(jìn)行的是嚴(yán)格相等比較(即 ===
),并且可以指定從哪個(gè)索引位置開始查找。
語法:
arr.includes(valueToFind[, fromIndex])
arr
:要進(jìn)行檢查的數(shù)組。valueToFind
:需要在數(shù)組中查找的值。fromIndex
(可選):開始查找的索引位置,默認(rèn)值為0
。若該值為負(fù)數(shù),則從數(shù)組末尾倒數(shù)相應(yīng)位置開始查找,但查找順序依然是從前往后。若fromIndex
的絕對(duì)值大于數(shù)組長度,會(huì)直接從索引0
開始查找。
示例:
// 示例 1:基本查找 const fruits = ['apple', 'banana', 'cherry']; const hasBanana = fruits.includes('banana'); console.log('數(shù)組:', fruits); console.log('數(shù)組中是否包含 "banana":', hasBanana); //數(shù)組: ['apple', 'banana', 'cherry'] //數(shù)組中是否包含 "banana": true // 示例 2:指定起始索引查找 const numbers = [10, 20, 30, 20]; const hasTwentyFromIndexTwo = numbers.includes(20, 2); console.log('數(shù)組:', numbers); console.log('從索引 2 開始查找,數(shù)組中是否包含 "20":', hasTwentyFromIndexTwo); //數(shù)組: [10, 20, 30, 20] //從索引 2 開始查找,數(shù)組中是否包含 "20": true // 示例 3:查找不存在的元素 const colors = ['red', 'green', 'blue']; const hasYellow = colors.includes('yellow'); console.log('數(shù)組:', colors); console.log('數(shù)組中是否包含 "yellow":', hasYellow); //數(shù)組: ['red', 'green', 'blue'] //數(shù)組中是否包含 "yellow": false // 示例 4:使用負(fù)索引查找 const letters = ['a', 'b', 'c', 'd']; const hasBFromNegativeIndex = letters.includes('b', -3); console.log('數(shù)組:', letters); console.log('從倒數(shù)第 3 個(gè)位置開始查找,數(shù)組中是否包含 "b":', hasBFromNegativeIndex); //數(shù)組: ['a', 'b', 'c', 'd'] //從倒數(shù)第 3 個(gè)位置開始查找,數(shù)組中是否包含 "b": true
15.sort()
在 JavaScript 中,sort()
是數(shù)組對(duì)象的一個(gè)方法,用于對(duì)數(shù)組的元素進(jìn)行排序。默認(rèn)情況下,sort()
方法會(huì)將數(shù)組元素轉(zhuǎn)換為字符串,然后按照 Unicode 編碼順序進(jìn)行排序。這意味著如果直接對(duì)數(shù)字?jǐn)?shù)組使用 sort()
方法,可能無法得到預(yù)期的數(shù)字大小排序結(jié)果。不過,你可以通過傳入一個(gè)比較函數(shù)來定義自定義的排序規(guī)則。sort()
方法會(huì)直接修改原數(shù)組,并返回排序后的數(shù)組。
語法:
arr.sort([compareFunction])
arr
:要進(jìn)行排序的數(shù)組。compareFunction
(可選):用于定義排序規(guī)則的比較函數(shù)。該函數(shù)接收兩個(gè)參數(shù)a
和b
,表示數(shù)組中的兩個(gè)元素,根據(jù)返回值的正負(fù)來決定元素的排序順序:- 如果返回值小于 0,則
a
會(huì)被排列到b
之前。 - 如果返回值等于 0,則
a
和b
的相對(duì)位置不變。 - 如果返回值大于 0,則
b
會(huì)被排列到a
之前。
- 如果返回值小于 0,則
示例:
// 示例 1:默認(rèn)排序(按 Unicode 編碼順序) const fruits = ['banana', 'apple', 'cherry']; const sortedFruits = fruits.sort(); console.log('原數(shù)組(已被修改):', fruits); console.log('排序后返回的數(shù)組:', sortedFruits); //原數(shù)組(已被修改): ['apple', 'banana', 'cherry'] //排序后返回的數(shù)組: ['apple', 'banana', 'cherry'] // 示例 2:對(duì)數(shù)字?jǐn)?shù)組使用默認(rèn)排序 const numbers = [10, 5, 2, 20]; const defaultSortedNumbers = numbers.sort(); console.log('原數(shù)組(已被修改):', numbers); console.log('默認(rèn)排序后返回的數(shù)組:', defaultSortedNumbers); //原數(shù)組(已被修改): [10, 2, 20, 5] //默認(rèn)排序后返回的數(shù)組: [10, 2, 20, 5] // 示例 3:使用比較函數(shù)對(duì)數(shù)字?jǐn)?shù)組進(jìn)行升序排序 const newNumbers = [10, 5, 2, 20]; const ascendingSortedNumbers = newNumbers.sort((a, b) => a - b); console.log('原數(shù)組(已被修改):', newNumbers); console.log('升序排序后返回的數(shù)組:', ascendingSortedNumbers); //原數(shù)組(已被修改): [2, 5, 10, 20] //升序排序后返回的數(shù)組: [2, 5, 10, 20] // 示例 4:使用比較函數(shù)對(duì)數(shù)字?jǐn)?shù)組進(jìn)行降序排序 const anotherNumbers = [10, 5, 2, 20]; const descendingSortedNumbers = anotherNumbers.sort((a, b) => b - a); console.log('原數(shù)組(已被修改):', anotherNumbers); console.log('降序排序后返回的數(shù)組:', descendingSortedNumbers); //原數(shù)組(已被修改): [20, 10, 5, 2] //降序排序后返回的數(shù)組: [20, 10, 5, 2]
16.reverse()
在 JavaScript 中,reverse()
是數(shù)組對(duì)象的一個(gè)方法,其主要功能是顛倒數(shù)組中元素的順序。該方法會(huì)直接修改原數(shù)組,將數(shù)組元素的排列順序反轉(zhuǎn),最后返回修改后的原數(shù)組
語法:
arr.reverse()
arr
:要進(jìn)行元素順序顛倒操作的數(shù)組。
示例:
// 示例 1:對(duì)普通數(shù)組使用 reverse() 方法 const numbers = [1, 2, 3, 4, 5]; const reversedNumbers = numbers.reverse(); console.log('原數(shù)組(已被修改):', numbers); console.log('反轉(zhuǎn)后返回的數(shù)組:', reversedNumbers); //原數(shù)組(已被修改): [5, 4, 3, 2, 1] //反轉(zhuǎn)后返回的數(shù)組: [5, 4, 3, 2, 1] // 示例 2:對(duì)字符串?dāng)?shù)組使用 reverse() 方法 const fruits = ['apple', 'banana', 'cherry']; const reversedFruits = fruits.reverse(); console.log('原數(shù)組(已被修改):', fruits); console.log('反轉(zhuǎn)后返回的數(shù)組:', reversedFruits); //原數(shù)組(已被修改): ['cherry', 'banana', 'apple'] //反轉(zhuǎn)后返回的數(shù)組: ['cherry', 'banana', 'apple']
17.forEach()
在 JavaScript 里,forEach()
是數(shù)組對(duì)象的一個(gè)方法,它用于對(duì)數(shù)組的每個(gè)元素執(zhí)行一次提供的函數(shù)。forEach()
方法沒有返回值,其主要目的是遍歷數(shù)組元素并對(duì)每個(gè)元素執(zhí)行特定操作。這個(gè)方法為數(shù)組中的每個(gè)元素依次調(diào)用一次你提供的回調(diào)函數(shù),并且不會(huì)改變?cè)瓟?shù)組。
語法:
arr.forEach(callback(currentValue[, index[, array]])[, thisArg])
arr
:要進(jìn)行遍歷的數(shù)組。callback
:為數(shù)組中每個(gè)元素執(zhí)行的函數(shù),該函數(shù)接收三個(gè)參數(shù):currentValue
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用forEach()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值。
示例:
// 示例 1:簡單遍歷數(shù)組并打印元素 const numbers = [1, 2, 3, 4, 5]; numbers.forEach(function (number) { console.log(number); }); //1 //2 //3 //4 //5 // 示例 2:使用索引和數(shù)組參數(shù) const fruits = ['apple', 'banana', 'cherry']; fruits.forEach(function (fruit, index, array) { console.log(`索引 ${index} 處的元素是 ${fruit},數(shù)組是 ${array}`); }); //索引 0 處的元素是 apple,數(shù)組是 apple,banana,cherry //索引 1 處的元素是 banana,數(shù)組是 apple,banana,cherry //索引 2 處的元素是 cherry,數(shù)組是 apple,banana,cherry // 示例 3:使用箭頭函數(shù)和累加操作 let sum = 0; const newNumbers = [10, 20, 30]; newNumbers.forEach((number) => { sum += number; }); console.log('數(shù)組元素的總和是:', sum); //數(shù)組元素的總和是: 60
18.map()
在 JavaScript 中,map()
是數(shù)組對(duì)象的一個(gè)方法,它用于創(chuàng)建一個(gè)新數(shù)組,新數(shù)組中的元素是原數(shù)組中每個(gè)元素經(jīng)過指定函數(shù)處理后的結(jié)果。也就是說,map()
方法會(huì)對(duì)原數(shù)組的每個(gè)元素依次調(diào)用你提供的回調(diào)函數(shù),并將回調(diào)函數(shù)的返回值作為新數(shù)組對(duì)應(yīng)位置的元素。該方法不會(huì)改變?cè)瓟?shù)組。
語法:
arr.map(callback(currentValue[, index[, array]])[, thisArg])
arr
:要進(jìn)行操作的原數(shù)組。callback
:為數(shù)組中每個(gè)元素執(zhí)行的函數(shù),該函數(shù)接收三個(gè)參數(shù):currentValue
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用map()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值。
示例:
// 示例 1:將數(shù)組中的每個(gè)元素乘以 2 const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(function (number) { return number * 2; }); console.log('原數(shù)組:', numbers); console.log('新數(shù)組(每個(gè)元素乘以 2):', doubledNumbers); //原數(shù)組: [1, 2, 3, 4, 5] //新數(shù)組(每個(gè)元素乘以 2): [2, 4, 6, 8, 10] // 示例 2:使用箭頭函數(shù)和索引參數(shù) const names = ['Alice', 'Bob', 'Charlie']; const nameWithIndex = names.map((name, index) => `${index + 1}. ${name}`); console.log('原數(shù)組:', names); console.log('新數(shù)組(添加索引):', nameWithIndex); //原數(shù)組: ['Alice', 'Bob', 'Charlie'] //新數(shù)組(添加索引): ['1. Alice', '2. Bob', '3. Charlie'] // 示例 3:處理對(duì)象數(shù)組 const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ]; const userAges = users.map(user => user.age); console.log('原數(shù)組:', users); console.log('新數(shù)組(只包含年齡):', userAges); //原數(shù)組: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ] //新數(shù)組(只包含年齡): [25, 30, 22]
19.copyWithin()
在 JavaScript 中,copyWithin()
是數(shù)組對(duì)象的一個(gè)方法,它用于在數(shù)組內(nèi)部將指定位置的元素復(fù)制到其他位置(覆蓋原有元素),并返回修改后的原數(shù)組。該方法會(huì)直接修改原數(shù)組,不會(huì)改變數(shù)組的長度。
語法:
arr.copyWithin(target[, start[, end]])
arr
:要進(jìn)行操作的數(shù)組。target
:復(fù)制序列到該位置。如果是負(fù)數(shù),target
將從數(shù)組末尾開始計(jì)算。start
(可選):開始復(fù)制元素的起始位置。默認(rèn)值為 0。如果是負(fù)數(shù),start
將從數(shù)組末尾開始計(jì)算。end
(可選):停止復(fù)制元素的結(jié)束位置(不包含該位置的元素)。默認(rèn)值為數(shù)組的長度。如果是負(fù)數(shù),end
將從數(shù)組末尾開始計(jì)算。
示例:
// 示例 1:簡單復(fù)制 const numbers = [1, 2, 3, 4, 5]; // 從索引 0 開始復(fù)制元素,復(fù)制到索引 3 的位置 const result = numbers.copyWithin(3); console.log('修改后的數(shù)組:', result); //修改后的數(shù)組: [1, 2, 3, 1, 2] // 示例 2:指定起始和結(jié)束位置復(fù)制 const letters = ['a', 'b', 'c', 'd', 'e']; // 從索引 1 開始復(fù)制元素,到索引 3 停止復(fù)制,復(fù)制到索引 0 的位置 const newResult = letters.copyWithin(0, 1, 3); console.log('修改后的數(shù)組:', newResult); //修改后的數(shù)組: ['b', 'c', 'c', 'd', 'e'] // 示例 3:使用負(fù)索引復(fù)制 const colors = ['red', 'green', 'blue', 'yellow', 'purple']; // 從倒數(shù)第 2 個(gè)元素開始復(fù)制,復(fù)制到倒數(shù)第 4 個(gè)元素的位置 const finalResult = colors.copyWithin(-4, -2); console.log('修改后的數(shù)組:', finalResult); //修改后的數(shù)組: ['red', 'yellow', 'purple', 'yellow', 'purple']
20.find()
在 JavaScript 中,find()
是數(shù)組對(duì)象的一個(gè)方法,它用于查找數(shù)組中滿足指定條件的第一個(gè)元素。該方法會(huì)對(duì)數(shù)組中的每個(gè)元素依次執(zhí)行你提供的測(cè)試函數(shù),一旦某個(gè)元素使測(cè)試函數(shù)返回 true
,find()
方法就會(huì)立即返回該元素;如果數(shù)組中沒有元素能使測(cè)試函數(shù)返回 true
,則返回 undefined
。find()
方法不會(huì)改變?cè)瓟?shù)組。
語法:
arr.find(callback(element[, index[, array]])[, thisArg])
arr
:要進(jìn)行查找操作的數(shù)組。callback
:用于測(cè)試每個(gè)元素的函數(shù),該函數(shù)接收三個(gè)參數(shù):element
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用find()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值。
示例:
// 示例 1:查找數(shù)組中第一個(gè)大于 5 的元素 const numbers = [1, 3, 7, 4, 9]; const firstGreaterThanFive = numbers.find(function (number) { return number > 5; }); console.log('數(shù)組:', numbers); console.log('數(shù)組中第一個(gè)大于 5 的元素:', firstGreaterThanFive); //數(shù)組: [1, 3, 7, 4, 9] //數(shù)組中第一個(gè)大于 5 的元素: 7 // 示例 2:使用箭頭函數(shù)查找對(duì)象數(shù)組中年齡大于 25 的第一個(gè)用戶 const users = [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ]; const firstUserOver25 = users.find(user => user.age > 25); console.log('數(shù)組:', users); console.log('數(shù)組中年齡大于 25 的第一個(gè)用戶:', firstUserOver25); //數(shù)組: [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ] //數(shù)組中年齡大于 25 的第一個(gè)用戶: { name: 'Bob', age: 28 } // 示例 3:查找不存在的元素 const letters = ['a', 'b', 'c']; const nonExistentElement = letters.find(letter => letter === 'd'); console.log('數(shù)組:', letters); console.log('查找結(jié)果:', nonExistentElement); //數(shù)組: ['a', 'b', 'c'] //查找結(jié)果: undefined
21.findIndex()
在 JavaScript 中,findIndex()
是數(shù)組對(duì)象的一個(gè)方法,其作用是查找數(shù)組中滿足指定條件的第一個(gè)元素的索引。它會(huì)對(duì)數(shù)組中的每個(gè)元素依次執(zhí)行你提供的測(cè)試函數(shù),一旦某個(gè)元素使測(cè)試函數(shù)返回 true
,findIndex()
方法就會(huì)立即返回該元素的索引;若數(shù)組中沒有元素能使測(cè)試函數(shù)返回 true
,則返回 -1
。此方法不會(huì)改變?cè)瓟?shù)組。
語法:
arr
:要進(jìn)行查找操作的數(shù)組。callback
:用于測(cè)試每個(gè)元素的函數(shù),該函數(shù)接收三個(gè)參數(shù):element
:當(dāng)前正在處理的數(shù)組元素。index
(可選):當(dāng)前元素的索引。array
(可選):調(diào)用findIndex()
方法的數(shù)組。
thisArg
(可選):執(zhí)行callback
函數(shù)時(shí)使用的this
值。
示例:
// 示例 1:查找數(shù)組中第一個(gè)大于 10 的元素的索引 const numbers = [5, 8, 12, 3, 15]; const index = numbers.findIndex(function (number) { return number > 10; }); console.log('數(shù)組:', numbers); console.log('數(shù)組中第一個(gè)大于 10 的元素的索引:', index); //數(shù)組: [5, 8, 12, 3, 15] //數(shù)組中第一個(gè)大于 10 的元素的索引: 2 // 示例 2:使用箭頭函數(shù)查找對(duì)象數(shù)組中年齡大于 25 的第一個(gè)用戶的索引 const users = [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ]; const userIndex = users.findIndex(user => user.age > 25); console.log('數(shù)組:', users); console.log('數(shù)組中年齡大于 25 的第一個(gè)用戶的索引:', userIndex); //數(shù)組: [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ] //數(shù)組中年齡大于 25 的第一個(gè)用戶的索引: 1 // 示例 3:查找不存在的元素的索引 const letters = ['a', 'b', 'c']; const nonExistentIndex = letters.findIndex(letter => letter === 'd'); console.log('數(shù)組:', letters); console.log('查找結(jié)果:', nonExistentIndex); //數(shù)組: ['a', 'b', 'c'] //查找結(jié)果: -1
總結(jié)
到此這篇關(guān)于前端JavaScript數(shù)組方法的文章就介紹到這了,更多相關(guān)前端js數(shù)組方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript實(shí)現(xiàn)的原生態(tài)兼容IE6可調(diào)可控滾動(dòng)文字功能詳解
這篇文章主要介紹了JavaScript實(shí)現(xiàn)的原生態(tài)兼容IE6可調(diào)可控滾動(dòng)文字功能,簡單說明了文字滾動(dòng)的實(shí)現(xiàn)原理并結(jié)合具體實(shí)例形式給出了javascript文字滾動(dòng)功能的具體實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-09-09關(guān)于HTTP傳輸中g(shù)zip壓縮的秘密探索分析
Gzip是一種流行的文件壓縮算法,現(xiàn)在的應(yīng)用十分廣泛,尤其是在Linux平臺(tái)。下面這篇文章主要給大家介紹了關(guān)于HTTP傳輸中g(shù)zip壓縮的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01Bootstrap模態(tài)框插入視頻的實(shí)現(xiàn)代碼
這篇文章主要介紹了Bootstrap模態(tài)框插入視頻的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-06-06IE瀏覽器不支持getElementsByClassName的解決方法
這篇文章主要介紹了IE瀏覽器不支持getElementsByClassName的解決方法,本文的方法比較完美的解決了這個(gè)問題,需要的朋友可以參考下2014-08-08抓取JavaScript動(dòng)態(tài)加載的內(nèi)容的方法總結(jié)
JavaScript動(dòng)態(tài)加載的內(nèi)容常見于現(xiàn)代Web應(yīng)用中,用于增強(qiáng)用戶體驗(yàn)和減少初始頁面加載時(shí)間,然而,這些動(dòng)態(tài)加載的內(nèi)容對(duì)于傳統(tǒng)的網(wǎng)頁抓取工具來說往往是不可見的,本文主要介紹了有JavaScript動(dòng)態(tài)加載的內(nèi)容如何抓取,需要的朋友可以參考下2024-09-09JavaScript如何正確聲明和使用變量詳細(xì)代碼實(shí)例
變量是程序在內(nèi)存中申請(qǐng)的一塊用來存放數(shù)據(jù)的空間,下面這篇文章主要給大家介紹了關(guān)于JavaScript如何正確聲明和使用變量的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07layui select動(dòng)態(tài)添加option的實(shí)例
下面小編就為大家分享一篇layui select動(dòng)態(tài)添加option的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03