美文网首页
javascript的所有循环遍历

javascript的所有循环遍历

作者: 只是为了一个梦想 | 来源:发表于2021-03-05 18:06 被阅读0次

for系列

for循环是js语言最原始的循环遍历方式,所有for循环均支持终止循环,JavaScript 提供了四种已知的终止循环执行的方法:break、continue、return 和 throw

  let a = 'hi'
  for(let i = 0 ;i < arr.length; i++){
      console.log(i) //返回索引0,1
  }

1、for...in...与for...of...

  1. for...in...返回索引,for...of返回值
  let a = 'start'
  for (let i in a){
      console.log(i)  //返回索引0,1,2,3,4,5
  }

  let a = [1,2,3]
  for (let i in a){
      console.log(i)  //返回索引0,1,2
  }

  let a = {one:1, two:2, three:3}
  for (let i in a){
      console.log(i)  //返回key one,two,three
  }
  let a = 'start'
  for (let i of a){
      console.log(i)  //返回索引s,t,a,r,t
  }

  let a = [1,2,3]
  for (let i of a){
      console.log(i)  //返回值 1,2,3
  }

  let a = {one:1, two:2, three:3}
  for (let i of a){
      console.log(i)  // a is not iterable
  }

// variable:每个迭代的属性值被分配给该变量。
// iterable:一个具有可枚举属性并且可以迭代的对象。
  for (variable of iterable) {
    statement
  }
  1. for...in... 不仅返回可枚举属性,也会返回原型链的继承的非枚举属性,for...of 返回可枚举属性,Object.keys只返回可枚举属性
Array.prototype.newArr = () => { }
let Arr = ['卢本伟', 'white', '55开']
for(let i in Arr){
    console.log(i) // 卢本伟、white、55开、newArr(非枚举属性)
}

Object.keys(Arr)  // 卢本伟、white、55开

for(let i of Arr){
    console.log(i) // 卢本伟、white、55开
}

ES6的系列

1、forEach、some、every,都是数组方法

foreach,适用于只是进行集合或数组遍历,返回子元素的值。

不支持 continue,用 return false 或 return true 代替。

不支持 break,用 try catch/every/some 代替。

  let a = [1,2,3]
  a.forEach(e=>{
    console.log(e) // 1, 2, 3
  })

  let obj = {one:1,two:2,three:3}
  obj.forEach(e=>{
      console.log(e)
  })
  // obj.forEach is not a function

2、map

map返回一个新数组,不会改变原数组,新数组的值为原数组调用函数处理后的值

let arr = [1,2,3,4,5,6]
arr.map(v=>{
  return v > 1   //[false,true,true,true,true],函数处理结果
})

相关文章

网友评论

      本文标题:javascript的所有循环遍历

      本文链接:https://www.haomeiwen.com/subject/kivtqltx.html