一、主要的数组方法:
join()
:用指定的分隔符将数组每一项拼接为字符串push()
:向数组的末尾添加新元素pop()
:删除数组的最后一项shift()
:删除数组的第一项unshift()
:向数组首位添加新元素slice()
:按照条件查找出其中的部分元素splice()
:对数组进行增删改fill()
: 方法能使用特定值填充数组中的一个或多个元素filter()
:“过滤”功能concat()
:用于连接两个或多个数组indexOf()
:检测当前值在数组中第一次出现的位置索引lastIndexOf()
:检测当前值在数组中最后一次出现的位置索引every()
:判断数组中每一项都是否满足条件some()
:判断数组中是否存在满足条件的项includes()
:判断一个数组是否包含一个指定的值sort()
:对数组的元素进行排序reverse()
:对数组进行倒序forEach()
:ES5 及以下循环遍历数组每一项map()
:ES6 循环遍历数组每一项copyWithin()
:用于从数组的指定位置拷贝元素到数组的另一个指定位置中find()
:返回匹配的值findIndex()
:返回匹配位置的索引toLocaleString()、toString()
:将数组转换为字符串flat()、flatMap()
:扁平化数组entries() 、keys() 、values()
:遍历数组
二、各类方法的具体使用
1.join()
在 JavaScript 里,join()
是数组对象的一个方法,其作用是把数组里的所有元素连接成一个字符串。你可以指定一个分隔符,该分隔符会被 插入到数组元素之间。若不指定分隔符,默认会使用逗号 ‘,’。
语法:
arr.join([separator])
arr
:需要连接元素的数组。separator
(可选):用于分隔数组元素的字符串。若省略该参数,数组元素会用逗号分隔。
示例:
//示例 1:使用默认分隔符 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()
是数组对象的一个方法,其主要作用是在数组的末尾添加一个或多个元素,并返回新数组的长度。该方法会直接修改原数组。
语法:
arr.push(element1[, ...[, elementN]])
arr
:要操作的数组。element1, ..., elementN
:要添加到数组末尾的一个或多个元素。
示例:
// 示例 1:添加单个元素 const animals = ['dog', 'cat']; const newLength = animals.push('rabbit'); console.log('新数组长度:', newLength); console.log('更新后的数组:', animals); //新数组长度: 3 //更新后的数组: ['dog', 'cat', 'rabbit'] // 示例 2:添加多个元素 const numbers = [1, 2, 3]; const updatedLength = numbers.push(4, 5); console.log('新数组长度:', updatedLength); console.log('更新后的数组:', numbers); //新数组长度: 5 //更新后的数组: [1, 2, 3, 4, 5]
3.pop()
在 JavaScript 里,pop()
是数组对象的一个方法。其作用是移除数组的最后一个元素,并且返回该被移除的元素。若数组为空,pop()
方法不会报错,而是返回 undefined
,同时此方法会直接对原数组进行修改。
语法:
arr.pop()
arr
:需要操作的数组。
示例:
// 示例 1:对非空数组使用 pop() 方法 const fruits = ['apple', 'banana', 'cherry']; const removedFruit = fruits.pop(); console.log('被移除的元素:', removedFruit); console.log('更新后的数组:', fruits); //被移除的元素: cherry //更新后的数组: ['apple', 'banana'] // 示例 2:对空数组使用 pop() 方法 const emptyArray = []; const result = emptyArray.pop(); console.log('返回值:', result); console.log('数组状态:', emptyArray); //返回值: undefined //数组状态: []
4.shift()
在 JavaScript 中,shift()
是数组对象的一个方法,其主要功能是移除数组的第一个元素,并返回该被移除的元素。如果数组为空,shift()
方法会返回 undefined
,同时该方法会直接修改原数组。
语法:
arr.shift()
arr
:要操作的数组。
示例:
// 示例 1:对非空数组使用 shift() 方法 const colors = ['red', 'green', 'blue']; const removedColor = colors.shift(); console.log('被移除的元素:', removedColor); console.log('更新后的数组:', colors); //被移除的元素: red //更新后的数组: ['green', 'blue'] // 示例 2:对空数组使用 shift() 方法 const emptyArr = []; const result = emptyArr.shift(); console.log('返回值:', result); console.log('数组状态:', emptyArr); //返回值: undefined //数组状态: []
5.unshift()
在 JavaScript 中,unshift()
是数组对象的一个方法,其作用是在数组的开头添加一个或多个元素,并返回新数组的长度。该方法会直接修改原数组。
语法:
arr.unshift(element1[, ...[, elementN]])
arr
:要操作的数组。element1, ..., elementN
:要添加到数组开头的一个或多个元素。
示例:
// 示例 1:添加单个元素 const numbers = [2, 3, 4]; const newLength = numbers.unshift(1); console.log('新数组的长度:', newLength); console.log('更新后的数组:', numbers); //新数组的长度: 4 //更新后的数组: [1, 2, 3, 4] // 示例 2:添加多个元素 const fruits = ['banana', 'cherry']; const updatedLength = fruits.unshift('apple', 'grape'); console.log('新数组的长度:', updatedLength); console.log('更新后的数组:', fruits); //新数组的长度: 4 //更新后的数组: ['apple', 'grape', 'banana', 'cherry']
6.slice()
在 JavaScript 中,slice()
是数组对象的一个方法,用于从原数组中提取出一部分元素,组成一个新的数组,而不会对原数组进行修改。
语法:
arr.slice([begin[, end]])
arr
:需要操作的数组。begin
(可选):提取元素的起始索引位置。如果省略该参数,默认从索引 0 开始。若为负数,则表示从数组末尾开始倒数的位置,例如-1
表示最后一个元素。end
(可选):提取元素的结束索引位置(不包含该索引对应的元素)。如果省略该参数,会提取从begin
到数组末尾的所有元素。若为负数,则表示从数组末尾开始倒数的位置。
示例:
// 示例 1:省略参数 const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']; const newFruits = fruits.slice(); console.log('原数组:', fruits); console.log('新数组:', newFruits); //原数组: ['apple', 'banana', 'cherry', 'date', 'elderberry'] //新数组: ['apple', 'banana', 'cherry', 'date', 'elderberry'] // 示例 2:指定 begin 参数 const numbers = [1, 2, 3, 4, 5]; const newNumbers = numbers.slice(2); console.log('原数组:', numbers); console.log('新数组:', newNumbers); //原数组: [1, 2, 3, 4, 5] //新数组: [3, 4, 5] // 示例 3:指定 begin 和 end 参数 const animals = ['cat', 'dog', 'elephant', 'fox', 'giraffe']; const newAnimals = animals.slice(1, 3); console.log('原数组:', animals); console.log('新数组:', newAnimals); //原数组: ['cat', 'dog', 'elephant', 'fox', 'giraffe'] //新数组: ['dog', 'elephant'] // 示例 4:使用负索引 const colors = ['red', 'green', 'blue', 'yellow', 'purple']; const newColors = colors.slice(-3, -1); console.log('原数组:', colors); console.log('新数组:', newColors); //原数组: ['red', 'green', 'blue', 'yellow', 'purple'] //新数组: ['blue', 'yellow']
7.fill()
在 JavaScript 中,fill()
是数组对象的一个方法,它可以用一个固定值填充数组中的一个或多个元素。该方法会直接修改原数组,并返回修改后的数组。
语法:
arr.fill(value[, start[, end]])
arr
:要操作的数组。value
:用来填充数组元素的值。start
(可选):开始填充的索引位置,默认为 0。如果是负数,则表示从数组末尾开始倒数的位置。end
(可选):结束填充的索引位置(不包含该索引对应的元素),默认为数组的长度。如果是负数,则表示从数组末尾开始倒数的位置。
示例:
// 示例 1:用一个值填充整个数组 const numbers = [1, 2, 3, 4, 5]; const filledNumbers = numbers.fill(0); console.log('原数组(已被修改):', numbers); console.log('填充后返回的数组:', filledNumbers); //原数组(已被修改): [0, 0, 0, 0, 0] //填充后返回的数组: [0, 0, 0, 0, 0] // 示例 2:指定开始和结束位置进行填充 const letters = ['a', 'b', 'c', 'd', 'e']; const filledLetters = letters.fill('x', 1, 3); console.log('原数组(已被修改):', letters); console.log('填充后返回的数组:', filledLetters); //原数组(已被修改): ['a', 'x', 'x', 'd', 'e'] //填充后返回的数组: ['a', 'x', 'x', 'd', 'e'] // 示例 3:使用负索引进行填充 const colors = ['red', 'green', 'blue', 'yellow', 'purple']; const filledColors = colors.fill('orange', -2); console.log('原数组(已被修改):', colors); console.log('填充后返回的数组:', filledColors); //原数组(已被修改): ['red', 'green', 'blue', 'orange', 'orange'] //填充后返回的数组: ['red', 'green', 'blue', 'orange', 'orange']
8.filter()
在 JavaScript 中,filter()
是数组对象的一个方法,其主要作用是创建一个新数组,新数组中的元素是原数组中满足指定条件的所有元素。filter()
方法不会改变原数组,而是返回一个新数组。
语法:
arr.filter(callback(element[, index[, array]])[, thisArg])
arr
:要操作的数组。callback
:用来测试数组每个元素的函数,它接收三个参数:element
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用filter()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值
示例:
// 示例 1:筛选出数组中的偶数 const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(function (number) { return number % 2 === 0; }); console.log('原数组:', numbers); console.log('筛选出的偶数数组:', evenNumbers); //原数组: [1, 2, 3, 4, 5, 6] //筛选出的偶数数组: [2, 4, 6] // 示例 2:使用箭头函数和索引筛选元素 const words = ['apple', 'banana', 'cherry', 'date']; const longWords = words.filter((word, index) => { return word.length > 5 && index % 2 === 0; }); console.log('原数组:', words); console.log('筛选出的长单词且索引为偶数的数组:', longWords); //原数组: ['apple', 'banana', 'cherry', 'date'] //筛选出的长单词且索引为偶数的数组: ['cherry'] // 示例 3:筛选出对象数组中满足条件的对象 const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ]; const adults = users.filter(user => user.age >= 25); console.log('原数组:', users); console.log('筛选出的成年人数组:', adults); //原数组: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ] //筛选出的成年人数组: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]
9.concat()
在 JavaScript 里,concat()
是数组对象的一个方法,其用途是把两个或多个数组连接起来,形成一个新的数组。此方法不会改变原数组,而是返回一个全新的数组,该数组包含了原数组以及被连接数组的所有元素。
语法:
const newArray = oldArray.concat(value1[, value2[, ...[, valueN]]])
oldArray
:调用concat()
方法的原始数组。value1, value2, ..., valueN
(可选):要连接到oldArray
末尾的数组或值。如果这些参数是数组,它们的元素会被逐个添加到新数组中;如果是其他值,则直接添加到新数组末尾。
示例:
// 示例 1:连接两个数组 const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const newArray = array1.concat(array2); console.log('原数组1:', array1); console.log('原数组2:', array2); console.log('连接后的新数组:', newArray); //原数组1: [1, 2, 3] //原数组2: [4, 5, 6] //连接后的新数组: [1, 2, 3, 4, 5, 6] // 示例 2:连接多个数组 const firstArray = ['a', 'b']; const secondArray = ['c', 'd']; const thirdArray = ['e', 'f']; const combinedArray = firstArray.concat(secondArray, thirdArray); console.log('原数组1:', firstArray); console.log('原数组2:', secondArray); console.log('原数组3:', thirdArray); console.log('连接后的新数组:', combinedArray); //原数组1: ['a', 'b'] //原数组2: ['c', 'd'] //原数组3: ['e', 'f'] //连接后的新数组: ['a', 'b', 'c', 'd', 'e', 'f'] // 示例 3:连接数组和值 const originalArray = [10, 20]; const newArrayWithValue = originalArray.concat(30, [40, 50]); console.log('原数组:', originalArray); console.log('连接后的新数组:', newArrayWithValue); //原数组: [10, 20] //连接后的新数组: [10, 20, 30, 40, 50]
10.indexOf()
在 JavaScript 中,indexOf()
是数组对象的一个方法,用于查找某个指定的值在数组中首次出现的索引位置。如果该值存在于数组中,就返回它的索引;若不存在,则返回 -1
。此方法进行的是严格相等比较(即 ===
)。
语法:
arr.indexOf(searchElement[, fromIndex])
arr
:要进行查找操作的数组。searchElement
:需要在数组中查找的元素。fromIndex
(可选):开始查找的索引位置,默认值为0
。若该值为负数,则从数组末尾倒数相应位置开始查找,但查找顺序依然是从前往后。
示例:
// 示例 1:基本查找 const fruits = ['apple', 'banana', 'cherry', 'banana']; const index = fruits.indexOf('banana'); console.log('数组:', fruits); console.log('"banana" 首次出现的索引:', index); //数组: ['apple', 'banana', 'cherry', 'banana'] //"banana" 首次出现的索引: 1 // 示例 2:指定起始索引查找 const numbers = [10, 20, 30, 20, 40]; const newIndex = numbers.indexOf(20, 2); console.log('数组:', numbers); console.log('从索引 2 开始查找,"20" 首次出现的索引:', newIndex); //数组: [10, 20, 30, 20, 40] //从索引 2 开始查找,"20" 首次出现的索引: 3 // 示例 3:查找不存在的元素 const colors = ['red', 'green', 'blue']; const nonExistentIndex = colors.indexOf('yellow'); console.log('数组:', colors); console.log('"yellow" 首次出现的索引:', nonExistentIndex); //数组: ['red', 'green', 'blue'] //"yellow" 首次出现的索引: -1
11.lastIndexOf()
在 JavaScript 中,lastIndexOf()
是数组对象的一个方法,其主要作用是查找指定元素在数组中最后一次出现的索引位置。如果数组中存在该元素,就返回其最后一次出现的索引;若不存在,则返回 -1
。该方法进行的是严格相等比较(即 ===
)。
语法:
arr.lastIndexOf(searchElement[, fromIndex])
arr
:要进行查找操作的数组。searchElement
:需要在数组中查找的元素。fromIndex
(可选):开始反向查找的索引位置。默认值为数组的长度减 1,也就是从数组的最后一个元素开始查找。若该值为负数,则从数组末尾倒数相应位置开始反向查找。
示例:
// 示例 1:基本查找 const fruits = ['apple', 'banana', 'cherry', 'banana']; const lastIndex = fruits.lastIndexOf('banana'); console.log('数组:', fruits); console.log('"banana" 最后一次出现的索引:', lastIndex); //数组: ['apple', 'banana', 'cherry', 'banana'] //"banana" 最后一次出现的索引: 3 // 示例 2:指定起始索引查找 const numbers = [10, 20, 30, 20, 40]; const newLastIndex = numbers.lastIndexOf(20, 2); console.log('数组:', numbers); console.log('从索引 2 开始反向查找,"20" 最后一次出现的索引:', newLastIndex); //数组: [10, 20, 30, 20, 40] //从索引 2 开始反向查找,"20" 最后一次出现的索引: 1 // 示例 3:查找不存在的元素 const colors = ['red', 'green', 'blue']; const nonExistentLastIndex = colors.lastIndexOf('yellow'); console.log('数组:', colors); console.log('"yellow" 最后一次出现的索引:', nonExistentLastIndex); //数组: ['red', 'green', 'blue'] //"yellow" 最后一次出现的索引: -1
12.every()
在 JavaScript 里,every()
是数组对象的一个方法。它用于检测数组里的所有元素是否都满足指定的条件。该方法会对数组中的每个元素执行一次提供的测试函数,若所有元素都使测试函数返回 true
,则 every()
方法返回 true
;只要有一个元素使测试函数返回 false
,就会立即停止遍历并返回 false
。此方法不会改变原数组。
语法:
arr.every(callback(element[, index[, array]])[, thisArg])
arr
:要进行检测的数组。callback
:用来测试每个元素的函数,它接收三个参数:element
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用every()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值。
示例:
// 示例 1:检查数组中的所有元素是否都大于 0 const numbers = [1, 2, 3, 4, 5]; const allPositive = numbers.every(function (number) { return number > 0; }); console.log('数组:', numbers); console.log('数组中的所有元素是否都大于 0:', allPositive); //数组: [1, 2, 3, 4, 5] //数组中的所有元素是否都大于 0: true // 示例 2:使用箭头函数检查数组中的所有元素长度是否都大于 3 const words = ['apple', 'banana', 'cherry']; const allLongWords = words.every(word => word.length > 3); console.log('数组:', words); console.log('数组中的所有元素长度是否都大于 3:', allLongWords); //数组: ['apple', 'banana', 'cherry'] //数组中的所有元素长度是否都大于 3: true // 示例 3:检查数组中的所有元素是否都是偶数 const mixedNumbers = [2, 4, 6, 7]; const allEven = mixedNumbers.every(num => num % 2 === 0); console.log('数组:', mixedNumbers); console.log('数组中的所有元素是否都是偶数:', allEven); //数组: [2, 4, 6, 7] //数组中的所有元素是否都是偶数: false
13.some()
在 JavaScript 中,some()
是数组对象的一个方法,用于检测数组中是否至少有一个元素满足指定的条件。它会对数组中的每个元素依次执行你提供的测试函数,只要有一个元素使测试函数返回 true
,some()
方法就会立即返回 true
;若所有元素都使测试函数返回 false
,则 some()
方法返回 false
。此方法不会改变原数组。
语法:
arr.some(callback(element[, index[, array]])[, thisArg])
arr
:要进行检测的数组。callback
:用于测试每个元素的函数,该函数接收三个参数:element
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用some()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值。
示例:
// 示例 1:检查数组中是否有元素大于 5 const numbers = [1, 3, 7, 4]; const hasGreaterThanFive = numbers.some(function (number) { return number > 5; }); console.log('数组:', numbers); console.log('数组中是否有元素大于 5:', hasGreaterThanFive); //数组: [1, 3, 7, 4] //数组中是否有元素大于 5: true // 示例 2:使用箭头函数检查数组中是否有元素长度小于 3 const words = ['apple', 'cat', 'banana']; const hasShortWord = words.some(word => word.length < 3); console.log('数组:', words); console.log('数组中是否有元素长度小于 3:', hasShortWord); //数组: ['apple', 'cat', 'banana'] //数组中是否有元素长度小于 3: false // 示例 3:检查数组中是否有偶数 const mixedNumbers = [1, 3, 5, 8]; const hasEvenNumber = mixedNumbers.some(num => num % 2 === 0); console.log('数组:', mixedNumbers); console.log('数组中是否有偶数:', hasEvenNumber); //数组: [1, 3, 5, 8] //数组中是否有偶数: true
14.includes()
在 JavaScript 里,includes()
是数组对象的一个方法,它用于判断数组是否包含某个指定的值。若包含则返回 true
,不包含则返回 false
。此方法进行的是严格相等比较(即 ===
),并且可以指定从哪个索引位置开始查找。
语法:
arr.includes(valueToFind[, fromIndex])
arr
:要进行检查的数组。valueToFind
:需要在数组中查找的值。fromIndex
(可选):开始查找的索引位置,默认值为0
。若该值为负数,则从数组末尾倒数相应位置开始查找,但查找顺序依然是从前往后。若fromIndex
的绝对值大于数组长度,会直接从索引0
开始查找。
示例:
// 示例 1:基本查找 const fruits = ['apple', 'banana', 'cherry']; const hasBanana = fruits.includes('banana'); console.log('数组:', fruits); console.log('数组中是否包含 "banana":', hasBanana); //数组: ['apple', 'banana', 'cherry'] //数组中是否包含 "banana": true // 示例 2:指定起始索引查找 const numbers = [10, 20, 30, 20]; const hasTwentyFromIndexTwo = numbers.includes(20, 2); console.log('数组:', numbers); console.log('从索引 2 开始查找,数组中是否包含 "20":', hasTwentyFromIndexTwo); //数组: [10, 20, 30, 20] //从索引 2 开始查找,数组中是否包含 "20": true // 示例 3:查找不存在的元素 const colors = ['red', 'green', 'blue']; const hasYellow = colors.includes('yellow'); console.log('数组:', colors); console.log('数组中是否包含 "yellow":', hasYellow); //数组: ['red', 'green', 'blue'] //数组中是否包含 "yellow": false // 示例 4:使用负索引查找 const letters = ['a', 'b', 'c', 'd']; const hasBFromNegativeIndex = letters.includes('b', -3); console.log('数组:', letters); console.log('从倒数第 3 个位置开始查找,数组中是否包含 "b":', hasBFromNegativeIndex); //数组: ['a', 'b', 'c', 'd'] //从倒数第 3 个位置开始查找,数组中是否包含 "b": true
15.sort()
在 JavaScript 中,sort()
是数组对象的一个方法,用于对数组的元素进行排序。默认情况下,sort()
方法会将数组元素转换为字符串,然后按照 Unicode 编码顺序进行排序。这意味着如果直接对数字数组使用 sort()
方法,可能无法得到预期的数字大小排序结果。不过,你可以通过传入一个比较函数来定义自定义的排序规则。sort()
方法会直接修改原数组,并返回排序后的数组。
语法:
arr.sort([compareFunction])
arr
:要进行排序的数组。compareFunction
(可选):用于定义排序规则的比较函数。该函数接收两个参数a
和b
,表示数组中的两个元素,根据返回值的正负来决定元素的排序顺序:- 如果返回值小于 0,则
a
会被排列到b
之前。 - 如果返回值等于 0,则
a
和b
的相对位置不变。 - 如果返回值大于 0,则
b
会被排列到a
之前。
- 如果返回值小于 0,则
示例:
// 示例 1:默认排序(按 Unicode 编码顺序) const fruits = ['banana', 'apple', 'cherry']; const sortedFruits = fruits.sort(); console.log('原数组(已被修改):', fruits); console.log('排序后返回的数组:', sortedFruits); //原数组(已被修改): ['apple', 'banana', 'cherry'] //排序后返回的数组: ['apple', 'banana', 'cherry'] // 示例 2:对数字数组使用默认排序 const numbers = [10, 5, 2, 20]; const defaultSortedNumbers = numbers.sort(); console.log('原数组(已被修改):', numbers); console.log('默认排序后返回的数组:', defaultSortedNumbers); //原数组(已被修改): [10, 2, 20, 5] //默认排序后返回的数组: [10, 2, 20, 5] // 示例 3:使用比较函数对数字数组进行升序排序 const newNumbers = [10, 5, 2, 20]; const ascendingSortedNumbers = newNumbers.sort((a, b) => a - b); console.log('原数组(已被修改):', newNumbers); console.log('升序排序后返回的数组:', ascendingSortedNumbers); //原数组(已被修改): [2, 5, 10, 20] //升序排序后返回的数组: [2, 5, 10, 20] // 示例 4:使用比较函数对数字数组进行降序排序 const anotherNumbers = [10, 5, 2, 20]; const descendingSortedNumbers = anotherNumbers.sort((a, b) => b - a); console.log('原数组(已被修改):', anotherNumbers); console.log('降序排序后返回的数组:', descendingSortedNumbers); //原数组(已被修改): [20, 10, 5, 2] //降序排序后返回的数组: [20, 10, 5, 2]
16.reverse()
在 JavaScript 中,reverse()
是数组对象的一个方法,其主要功能是颠倒数组中元素的顺序。该方法会直接修改原数组,将数组元素的排列顺序反转,最后返回修改后的原数组
语法:
arr.reverse()
arr
:要进行元素顺序颠倒操作的数组。
示例:
// 示例 1:对普通数组使用 reverse() 方法 const numbers = [1, 2, 3, 4, 5]; const reversedNumbers = numbers.reverse(); console.log('原数组(已被修改):', numbers); console.log('反转后返回的数组:', reversedNumbers); //原数组(已被修改): [5, 4, 3, 2, 1] //反转后返回的数组: [5, 4, 3, 2, 1] // 示例 2:对字符串数组使用 reverse() 方法 const fruits = ['apple', 'banana', 'cherry']; const reversedFruits = fruits.reverse(); console.log('原数组(已被修改):', fruits); console.log('反转后返回的数组:', reversedFruits); //原数组(已被修改): ['cherry', 'banana', 'apple'] //反转后返回的数组: ['cherry', 'banana', 'apple']
17.forEach()
在 JavaScript 里,forEach()
是数组对象的一个方法,它用于对数组的每个元素执行一次提供的函数。forEach()
方法没有返回值,其主要目的是遍历数组元素并对每个元素执行特定操作。这个方法为数组中的每个元素依次调用一次你提供的回调函数,并且不会改变原数组。
语法:
arr.forEach(callback(currentValue[, index[, array]])[, thisArg])
arr
:要进行遍历的数组。callback
:为数组中每个元素执行的函数,该函数接收三个参数:currentValue
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用forEach()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值。
示例:
// 示例 1:简单遍历数组并打印元素 const numbers = [1, 2, 3, 4, 5]; numbers.forEach(function (number) { console.log(number); }); //1 //2 //3 //4 //5 // 示例 2:使用索引和数组参数 const fruits = ['apple', 'banana', 'cherry']; fruits.forEach(function (fruit, index, array) { console.log(`索引 ${index} 处的元素是 ${fruit},数组是 ${array}`); }); //索引 0 处的元素是 apple,数组是 apple,banana,cherry //索引 1 处的元素是 banana,数组是 apple,banana,cherry //索引 2 处的元素是 cherry,数组是 apple,banana,cherry // 示例 3:使用箭头函数和累加操作 let sum = 0; const newNumbers = [10, 20, 30]; newNumbers.forEach((number) => { sum += number; }); console.log('数组元素的总和是:', sum); //数组元素的总和是: 60
18.map()
在 JavaScript 中,map()
是数组对象的一个方法,它用于创建一个新数组,新数组中的元素是原数组中每个元素经过指定函数处理后的结果。也就是说,map()
方法会对原数组的每个元素依次调用你提供的回调函数,并将回调函数的返回值作为新数组对应位置的元素。该方法不会改变原数组。
语法:
arr.map(callback(currentValue[, index[, array]])[, thisArg])
arr
:要进行操作的原数组。callback
:为数组中每个元素执行的函数,该函数接收三个参数:currentValue
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用map()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值。
示例:
// 示例 1:将数组中的每个元素乘以 2 const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(function (number) { return number * 2; }); console.log('原数组:', numbers); console.log('新数组(每个元素乘以 2):', doubledNumbers); //原数组: [1, 2, 3, 4, 5] //新数组(每个元素乘以 2): [2, 4, 6, 8, 10] // 示例 2:使用箭头函数和索引参数 const names = ['Alice', 'Bob', 'Charlie']; const nameWithIndex = names.map((name, index) => `${index + 1}. ${name}`); console.log('原数组:', names); console.log('新数组(添加索引):', nameWithIndex); //原数组: ['Alice', 'Bob', 'Charlie'] //新数组(添加索引): ['1. Alice', '2. Bob', '3. Charlie'] // 示例 3:处理对象数组 const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ]; const userAges = users.map(user => user.age); console.log('原数组:', users); console.log('新数组(只包含年龄):', userAges); //原数组: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 22 } ] //新数组(只包含年龄): [25, 30, 22]
19.copyWithin()
在 JavaScript 中,copyWithin()
是数组对象的一个方法,它用于在数组内部将指定位置的元素复制到其他位置(覆盖原有元素),并返回修改后的原数组。该方法会直接修改原数组,不会改变数组的长度。
语法:
arr.copyWithin(target[, start[, end]])
arr
:要进行操作的数组。target
:复制序列到该位置。如果是负数,target
将从数组末尾开始计算。start
(可选):开始复制元素的起始位置。默认值为 0。如果是负数,start
将从数组末尾开始计算。end
(可选):停止复制元素的结束位置(不包含该位置的元素)。默认值为数组的长度。如果是负数,end
将从数组末尾开始计算。
示例:
// 示例 1:简单复制 const numbers = [1, 2, 3, 4, 5]; // 从索引 0 开始复制元素,复制到索引 3 的位置 const result = numbers.copyWithin(3); console.log('修改后的数组:', result); //修改后的数组: [1, 2, 3, 1, 2] // 示例 2:指定起始和结束位置复制 const letters = ['a', 'b', 'c', 'd', 'e']; // 从索引 1 开始复制元素,到索引 3 停止复制,复制到索引 0 的位置 const newResult = letters.copyWithin(0, 1, 3); console.log('修改后的数组:', newResult); //修改后的数组: ['b', 'c', 'c', 'd', 'e'] // 示例 3:使用负索引复制 const colors = ['red', 'green', 'blue', 'yellow', 'purple']; // 从倒数第 2 个元素开始复制,复制到倒数第 4 个元素的位置 const finalResult = colors.copyWithin(-4, -2); console.log('修改后的数组:', finalResult); //修改后的数组: ['red', 'yellow', 'purple', 'yellow', 'purple']
20.find()
在 JavaScript 中,find()
是数组对象的一个方法,它用于查找数组中满足指定条件的第一个元素。该方法会对数组中的每个元素依次执行你提供的测试函数,一旦某个元素使测试函数返回 true
,find()
方法就会立即返回该元素;如果数组中没有元素能使测试函数返回 true
,则返回 undefined
。find()
方法不会改变原数组。
语法:
arr.find(callback(element[, index[, array]])[, thisArg])
arr
:要进行查找操作的数组。callback
:用于测试每个元素的函数,该函数接收三个参数:element
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用find()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值。
示例:
// 示例 1:查找数组中第一个大于 5 的元素 const numbers = [1, 3, 7, 4, 9]; const firstGreaterThanFive = numbers.find(function (number) { return number > 5; }); console.log('数组:', numbers); console.log('数组中第一个大于 5 的元素:', firstGreaterThanFive); //数组: [1, 3, 7, 4, 9] //数组中第一个大于 5 的元素: 7 // 示例 2:使用箭头函数查找对象数组中年龄大于 25 的第一个用户 const users = [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ]; const firstUserOver25 = users.find(user => user.age > 25); console.log('数组:', users); console.log('数组中年龄大于 25 的第一个用户:', firstUserOver25); //数组: [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ] //数组中年龄大于 25 的第一个用户: { name: 'Bob', age: 28 } // 示例 3:查找不存在的元素 const letters = ['a', 'b', 'c']; const nonExistentElement = letters.find(letter => letter === 'd'); console.log('数组:', letters); console.log('查找结果:', nonExistentElement); //数组: ['a', 'b', 'c'] //查找结果: undefined
21.findIndex()
在 JavaScript 中,findIndex()
是数组对象的一个方法,其作用是查找数组中满足指定条件的第一个元素的索引。它会对数组中的每个元素依次执行你提供的测试函数,一旦某个元素使测试函数返回 true
,findIndex()
方法就会立即返回该元素的索引;若数组中没有元素能使测试函数返回 true
,则返回 -1
。此方法不会改变原数组。
语法:
arr
:要进行查找操作的数组。callback
:用于测试每个元素的函数,该函数接收三个参数:element
:当前正在处理的数组元素。index
(可选):当前元素的索引。array
(可选):调用findIndex()
方法的数组。
thisArg
(可选):执行callback
函数时使用的this
值。
示例:
// 示例 1:查找数组中第一个大于 10 的元素的索引 const numbers = [5, 8, 12, 3, 15]; const index = numbers.findIndex(function (number) { return number > 10; }); console.log('数组:', numbers); console.log('数组中第一个大于 10 的元素的索引:', index); //数组: [5, 8, 12, 3, 15] //数组中第一个大于 10 的元素的索引: 2 // 示例 2:使用箭头函数查找对象数组中年龄大于 25 的第一个用户的索引 const users = [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ]; const userIndex = users.findIndex(user => user.age > 25); console.log('数组:', users); console.log('数组中年龄大于 25 的第一个用户的索引:', userIndex); //数组: [ { name: 'Alice', age: 22 }, { name: 'Bob', age: 28 }, { name: 'Charlie', age: 20 } ] //数组中年龄大于 25 的第一个用户的索引: 1 // 示例 3:查找不存在的元素的索引 const letters = ['a', 'b', 'c']; const nonExistentIndex = letters.findIndex(letter => letter === 'd'); console.log('数组:', letters); console.log('查找结果:', nonExistentIndex); //数组: ['a', 'b', 'c'] //查找结果: -1
总结
到此这篇关于前端JavaScript数组方法的文章就介绍到这了,更多相关前端js数组方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/3395314kg.htm
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
暂无评论内容