循环的几种类型 (遍历数组或对象)

数组遍历的几种方式:

1.for循环

最简单的一种循环遍历方法,也是使用频率最高的一种。

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

2.for..in

这个循环用的人也很多,但是效率最低(输出的 key 是数组索引)

let arr = ['我', '是', '谁', '我', '在', '哪'];
for(let key in arr) {
  console.log(key);
}
下面是打印的结果:
0
1
2
3
4
5

3.for...of..

虽然性能要好于 for...in...,但仍然比不上普通的 for 循环(不能循环对象)

let arr = ['我', '是', '谁', '我', '在', '哪'];
for(let it of arr) {
  console.log(it);
}
打印的结果:
我
是
谁
我
在
哪

4.forEach

有几个元素就回调几次。参数一数组元素,参数二为数组元素索引,参数三数组自己。

该方法是数组自带的遍历方法,虽然使用频率略高,但是性能仍然比普通循环略低。

let arr = [1, 2, 3, 4, 5, 6];
arr.forEach(function (it, index, array) {
  console.log(it);
  console.log(array);
})

5.map

遍历每一个元素并且返回对应的元素(返回处理后的元素),返回的新数组和旧数组的长度是一样的

该方法使用比较广泛,但其性能还不如 forEach。

let arr = [1, 2, 3, 4, 5, 6];
let newArr = arr.map(function (item, index) {
  return item * item;
})
console.log(newArr);

打印结果为:
[1, 4, 9, 16, 25, 36]

6.filter 

遍历数组,过滤出符合条件的元素并返回一个新数组。

let arr = [
  { id: 1, name: '买笔', done: true },
  { id: 2, name: '买笔记本', done: true },
  { id: 3, name: '练字', done: false }
]
    
let newArr = arr.filter(function (item, index) {
  return item.done;
})
console.log(newArr);

打印结果为: 
[
    {id: 1, name: '买笔', done: true}
    {id: 2, name: '买笔记本', done: true}
]

7.some

遍历数组,只要有一个以上的元素满足条件就返回 true,否则返回 false

let arr = [
  { id: 1, name: '买笔', done: true },
  { id: 2, name: '买笔记本', done: true },
  { id: 3, name: '练字', done: false }
]

let bool = arr.some(function (item, index) {
  return item.done;
})
console.log(bool);

打印结果为: 
true

 8.every

遍历数组,每一个元素都满足条件 则返回 true,否则返回 false

let arr = [
  { id: 1, name: '买笔', done: true },
  { id: 2, name: '买笔记本', done: true },
  { id: 3, name: '练字', done: false }
]

let bool = arr.every(function (item, index) {
  return item.done;
})
console.log(bool);

打印结果为:
false

9.find(es6)

遍历数组,返回符合条件的第一个元素,如果没有符合条件的元素则返回 undefined

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

let num = arr.find(function (item, index) {
  return item === 3;
})
console.log(num);

打印结果为:
3

10.findIndex(ES6)

遍历数组,返回符合条件的第一个元素的索引,如果没有符合条件的元素则返回 -1

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

let num = arr.findIndex(function (item) {
  return item === 3;
})
console.log(num);

打印结果为:
4

11.reduce 

reduce 方法接收两个参数,第一个参数是回调函数(callback) ,第二个参数是初始值(initialValue)。

作为计算数组属性的总和

const list  = [
  { name: 'left', width: 20 },
  { name: 'center', width: 70 },
  { name: 'right', width: 10 },
];
const total = list.reduce((currentTotal, item) => {//第一个回调函数, 里面的参数1:currentTotal是每次累加的值   第二个参数item是数组list的元素
  return currentTotal + item.width;
}, 0);//0就是第二个参数,就是初始化的值
console.log(total)

打印结果为:
100

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值