js中常见的数组方法总结

在 JavaScript 中,数组是一种非常常用的数据结构,用于存储和操作一系列有序的元素。以下是一些在 JavaScript 中常用的数组操作方法:

1. 创建数组:

const arr = [1, 2, 3, 4, 5];

2. 访问数组元素:

console.log(arr[0]); // 输出 1

3. 修改数组元素:

arr[0] = 10;
console.log(arr); // 输出 [10, 2, 3, 4, 5]

4. 获取数组长度:

console.log(arr.length); // 输出 5

5. 遍历数组:

arr.forEach((element, index) => {
  console.log(`Element at index ${index}: ${element}`);
});

6. 添加元素到数组末尾:

arr.push(6);
console.log(arr); // 输出 [10, 2, 3, 4, 5, 6]

7. 移除数组末尾的元素:

arr.pop();
console.log(arr); // 输出 [10, 2, 3, 4, 5]

8. 添加元素到数组开头:

arr.unshift(0);
console.log(arr); // 输出 [0, 10, 2, 3, 4, 5]

9. 移除数组开头的元素:

arr.shift();
console.log(arr); // 输出 [10, 2, 3, 4, 5]

10. 截取数组的一部分:

const newArr = arr.slice(1, 4);
console.log(newArr); // 输出 [2, 3, 4]

11. 合并两个数组:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArr = arr1.concat(arr2);
console.log(combinedArr); // 输出 [1, 2, 3, 4, 5, 6]

12. 查找数组中的元素:

const index = arr.indexOf(3);
console.log(index); // 输出 2

13. 使用 map 对数组进行操作:

const doubledArr = arr.map((element) => element * 2);
console.log(doubledArr); // 输出 [20, 4, 6, 8, 10]

14. 使用 filter 筛选数组:

const evenArr = arr.filter((element) => element % 2 === 0);
console.log(evenArr); // 输出 [10, 2, 4]

15. 使用 reduce 对数组进行累计操作:

const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出 24

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值