it编程 > 编程语言 > Javascript

前端JavaScript数组方法总结(非常详细!)

9人参与 2025-04-24 Javascript

一、主要的数组方法:

二、各类方法的具体使用

1.join()

在 javascript 里,join() 是数组对象的一个方法,其作用是把数组里的所有元素连接成一个字符串。你可以指定一个分隔符,该分隔符会被 插入到数组元素之间。若不指定分隔符,默认会使用逗号 ‘,’。

语法:

arr.join([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]])

示例:

// 示例 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()

示例:

// 示例 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()

示例:

// 示例 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]])

示例:

// 示例 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]])

示例:

// 示例 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]])

示例:

// 示例 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])

示例:

// 示例 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]]])

示例:

// 示例 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])

示例:

// 示例 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])

示例:

// 示例 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])

示例:

// 示例 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() 是数组对象的一个方法,用于检测数组中是否至少有一个元素满足指定的条件。它会对数组中的每个元素依次执行你提供的测试函数,只要有一个元素使测试函数返回 truesome() 方法就会立即返回 true;若所有元素都使测试函数返回 false,则 some() 方法返回 false。此方法不会改变原数组。

语法:

arr.some(callback(element[, index[, array]])[, thisarg])

示例:

// 示例 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])

示例:

// 示例 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])

示例:

// 示例 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()

示例:

// 示例 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])

示例:

// 示例 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])

示例:

// 示例 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]])

示例:

// 示例 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() 是数组对象的一个方法,它用于查找数组中满足指定条件的第一个元素。该方法会对数组中的每个元素依次执行你提供的测试函数,一旦某个元素使测试函数返回 truefind() 方法就会立即返回该元素;如果数组中没有元素能使测试函数返回 true,则返回 undefinedfind() 方法不会改变原数组。

语法:

arr.find(callback(element[, index[, array]])[, thisarg])

示例:

// 示例 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() 是数组对象的一个方法,其作用是查找数组中满足指定条件的第一个元素的索引。它会对数组中的每个元素依次执行你提供的测试函数,一旦某个元素使测试函数返回 truefindindex() 方法就会立即返回该元素的索引;若数组中没有元素能使测试函数返回 true,则返回 -1。此方法不会改变原数组。

语法:

示例:

// 示例 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数组方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Webpack打包速度优化方案汇总

04-24

一文详解如何将Javascript打包成exe可执行文件

04-24

前端请求全面解析之AJAX、Axios 与 Fetch的使用详解与代码示例

04-24

JavaScript中if、else if、else和switch的语法、用法及注意事项

04-24

前端下载文件时如何后端返回的文件流一些常见方法

04-24

一篇文章详细讲解JavaScript中的this(普通函数、箭头函数、 函数运用)

04-24

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论