一系列 JS 数组操作分类

这篇博客详细介绍了JavaScript中数组的各种操作,包括遍历方法如for、for...of、for...in循环,以及forEach、map、filter等。此外,还讨论了改变原始数组的方法如sort、reverse、push、pop等,数组的映射、连接、截取、转换和扁平化等实用技巧。
摘要由CSDN通过智能技术生成

数组的遍历

for 循环

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
   
  console.log(arr[i]);
}
// 1
// 2
// 3
// 4
// 5

for…of 循环(遍历的是value)

let arr = ['Chocolate', 'zhlll', 'lionkk'];

for (let val of arr) {
   
  console.log(val);
}
// Chocolate
// zhlll
// lionkk

for…in 循环(遍历的是key。对于数组,key对应的是数组的下标索引)

let arr = ['Chocolate', 'zhlll', 'lionkk'];

for (let key in arr) {
   
  console.log(key);
}
// 0
// 1
// 2

array.forEach(callback(currentValue, index, arr), thisArg)

callback:为数组中每个元素执行的函数,该函数接收一至三个参数

  1. currentValue: 数组中正在处理的当前元素

  2. index (可选): 数组中正在处理的当前元素的索引

  3. arr (可选): forEach() 方法正在操作的数组

thisArg 可选:当执行回调函数callback,用作this值

let arr = ['Chocolate', 'zhlll', 'lionkk'];

arr.forEach((cur) => {
   
  console.log(cur);
})
// Chocolate
// zhlll
// lionkk
以下遍历方法返回一个新数组:
array.map() & array.filter() & array.keys() & array.values() & array.entries()

array.map(callback(currentValue, index, arr), thisArg)参数含义同上

定义:返回一个新数组,其结果是该数组中的每个元素调用一次回调函数后的返回值。

let arr = ['Chocolate', 'zhlll', 'lionkk'];

let newArr = arr.map(function (cur, index, arr) {
   
  console.log(cur, index, arr);
  return cur + index;
})
// Chocolate 0 [ 'Chocolate', 'zhlll', 'lionkk' ]
// zhlll 1 [ 'Chocolate', 'zhlll', 'lionkk' ]
// lionkk 2 [ 'Chocolate', 'zhlll', 'lionkk' ]

console.log(newArr)
// [ 'Chocolate0', 'zhlll1', 'lionkk2' ]

array.filter(callback(currentValue, index, arr), thisArg)参数含义同上

定义:返回一个新数组, 其包含该数组中的每个元素调用一次所提供函数后满足条件的所有元素。

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

let newArr = arr.filter(function (cur, index) {
   
  console.log(cur, index);
  return cur % 2 == 0;
})
// 1 0
// 2 1
// 3 2
// 4 3
// 5 4
console.log(newArr); // [ 2, 4 ]

array.keys() 与 array.values() 与 array.entries()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值