Blogger Information
Blog 94
fans 0
comment 0
visits 91872
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】 JS流程控制之:循环
可乐随笔
Original
621 people have browsed it

JS流程控制之:循环

  • 循环三要素
    1. 初始化:循环入口,从那开始
    1. 循环之条件:到那结束
    1. 更新循环条件:避免进入死循环

数组:元素的有序集合
对象:元素的无序集合

1. while

  1. // 语法:while (条件) { 更新条件},注:初始化在while外部
  2. const arr = [10, 20, 30]
  3. console.log(arr.length)
  4. console.log('-----------------')
  5. // 1.初始化:循环入口
  6. // 将索引指向第一数组成员
  7. let i = 0
  8. while (i < arr.length) {
  9. console.log(arr[i])
  10. // i += 1
  11. i++
  12. }
  13. console.log('-----------------')
  14. //do while
  15. i = 0
  16. do {
  17. console.log(arr[i])
  18. // i += 1
  19. i++
  20. } while (i < arr.length)
  21. console.log('-----------------')

2. for循环是while的语法糖

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

3. for-of (快速遍历数组)

  1. for (let item of arr) {
  2. console.log(item)
  3. }
  4. console.log('-----------------')

4. forEach (最常见的遍历数组的方法)

  1. // arr.forEach(function (item, index, arr) {
  2. // console.log(item, index, arr)
  3. // })
  4. // * 一般遍历数组,只需要写第一个参数
  5. // arr.forEach(function (item) {
  6. // console.log(item)
  7. // })
  8. // * 简化,箭头函数
  9. arr.forEach(item => console.log(item))
  10. // * map : map 有返回值,forEach没有
  11. // let result = arr.map(item => item)
  12. // console.log(result)
  13. console.log('-----------------')

5. for in 遍历对象

  1. const user ={
  2. name: 'admin',
  3. 'my email':'nx99@qq.com',
  4. show(){
  5. return `${this.name}: ${this["my email"]}`
  6. }
  7. }
  8. for (let prop in user){
  9. console.log(user[prop])
  10. }
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!