js中循环数组的几种方法和优化 forEach和map循环的退出方式

let array = []
for (let index = 0; index <10000000; index++) {
  array.push(index)
  
}
// 第一种
console.time('时间for')
for (let index = 0; index < array.length; index++) {
      const a = array[index]
}
console.timeEnd('时间for')
// 第一种 优化
console.time('优化 时间for')
//这种方式在于第一次就把长度付给了变量 而不用每次都访问数组长度
for (let index = 0, len = array.length; index < len; index++) {
      const a = array[index]
}
console.timeEnd('优化 时间for')
// 第一种 优化2
console.time('优化2 时间for')
for (let index = array.length; index > -1; index--) {
      const a = array[index]
}
console.timeEnd('优化2 时间for')
//第二种
console.time('时间forEach')
array.forEach((item,index) =>{
     return  item
})
console.timeEnd('时间forEach')
//第三种
console.time('时间map')
let array1 = array.map((item,index) =>{
      return item
})
console.timeEnd('时间map')
// forEach和map两种方式很相似 1、都不会改变原数组 2、map会通过运算返回一个新的数组 而forEach不会返回新的数组

// 第四种
//for in 是用来遍历对象的 用来遍历数组也行 遍历出来的是数组和对象的key 而且假如数组有私有属性 for in 也可以访问 而普通for和for of都不行
console.time('时间forin')
for (const key in array) {
  const a = array[key]
}
console.timeEnd('时间forin')

// 第五种
// for of 是es6提出的行方法 遍历的是数组本身
console.time('时间forof')
for (const item of array) {
  const a = item
}
console.timeEnd('时间forof')


// 总结 1、原生的 for性能最好 for in最差 2、for in 能访问私有属性 3、map和foEach不能被break和continue打断 map会返回新的数组而forEach则不会

//js中forEach和map循环的退出方式
try{
  // 执行到第3次,结束循环
  array.forEach(function(item,index) {
    if(index == 2){
    //手动抛出异常 终止循环
    // throw 表示抛出的异常
      throw new Error("EndIterative");
    }
  });
}catch(e){
  console.log(e.message );
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript 循环数组方式有以下几种: 1. for 循环 使用 for 循环可以遍历数组的每个元素。可以通过数组的 length 属性确定循环次数。例如: ``` var arr = [1, 2, 3]; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); } ``` 2. forEach 方法 可以使用 forEach 方法来遍历数组的每个元素。它接受一个回调函数作为参数,回调函数的参数分别为当前遍历的元素、当前遍历的索引、原始数组。例如: ``` var arr = [1, 2, 3]; arr.forEach(function(item, index, array) { console.log(item); }); ``` 3. for...in 循环 使用 for...in 循环可以遍历数组的每个属性。它返回的是属性名,需要通过属性名获取对应的属性值。例如: ``` var arr = [1, 2, 3]; for (var index in arr) { console.log(arr[index]); } ``` 需要注意的是,使用 for...in 循环遍历数组时,可能会遍历到一些非数字类型的属性,例如数组方法、原型链上的属性等,所以需要通过 hasOwnProperty 方法来判断属性是否为对象自身的属性。例如: ``` var arr = [1, 2, 3]; for (var index in arr) { if (arr.hasOwnProperty(index)) { console.log(arr[index]); } } ``` 4. for...of 循环 使用 for...of 循环可以遍历数组的每个元素。它返回的是元素值,而不是索引或属性名。例如: ``` var arr = [1, 2, 3]; for (var item of arr) { console.log(item); } ``` 以上是 JavaScript 常用的几种循环数组方式,根据不同的需求选择合适的方式可以使代码更加简洁、易读。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值