前端JS数组常用方法

数组方法

pushpop
  • push:在数组末尾添加一个或多个元素,并返回数组的新长度。
  • pop:从数组末尾移除一个元素,并返回该元素。
let arr = [1, 2, 3];
arr.push(4);  // [1, 2, 3, 4]
arr.pop();    // 4, arr变为 [1, 2, 3]
shiftunshift
  • shift:从数组开头移除一个元素,并返回该元素。
  • unshift:在数组开头添加一个或多个元素,并返回数组的新长度。
let arr = [1, 2, 3];
arr.unshift(0);  // [0, 1, 2, 3]
arr.shift();     // 0, arr变为 [1, 2, 3]
map

创建一个新数组,其结果是对原数组中的每个元素调用一个提供的函数后的返回值。

let arr = [1, 2, 3];
let newArr = arr.map(x => x * 2);  // [2, 4, 6]
filter

创建一个新数组,其包含通过所提供函数实现的测试的所有元素。

let arr = [1, 2, 3, 4];
let newArr = arr.filter(x => x > 2);  // [3, 4]
reduce

对数组中的每个元素执行一个提供的 reducer 函数,将其结果汇总为单个返回值。

let arr = [1, 2, 3, 4];
let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);  // 10
reverse

反转数组元素的顺序。原地修改而不是创建新数组。

const array = [1, 2, 3, 4, 5];
const reversedArray = array.reverse();

console.log(reversedArray); // 输出: [5, 4, 3, 2, 1]
console.log(array); // 输出: [5, 4, 3, 2, 1](原数组也被修改了)

反转字符串:将字符串转换为数组,反转后再转换为字符串。

const str = "hello";
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // "olleh"

forEach

对数组中的每个元素执行一次提供的函数。

let arr = [1, 2, 3];
arr.forEach(x => console.log(x));
// 输出:
// 1
// 2
// 3
findfindIndex
  • find:返回数组中满足提供的测试函数的第一个元素的值。
  • findIndex:返回数组中满足提供的测试函数的第一个元素的索引。
let arr = [1, 2, 3, 4];
let found = arr.find(x => x > 2);  // 3
let foundIndex = arr.findIndex(x => x > 2);  // 2

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值