首页 > 其他 > 详细

forEach,for..... in,for循环的区别

时间:2020-04-06 19:57:47      阅读:64      评论:0      收藏:0      [点我收藏+]

向来心是看客心 奈何人是局中人

 

先写一个数组:

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

    console.log(arr);

 

 技术分享图片

一、forEach(): 

代码:

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

    arr.forEach(function(i){

        console.log(i)

    })

 

输出结果:

技术分享图片

二、for..... in():

代码:

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

    for(var i in arr){

        console.log(i)

    }

 

输出结果:

 

 技术分享图片

输出的竟然是索引下标。

换种方法试下:

代码:

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

    for(var i in arr){

        console.log(arr[i])

    }

 

输出结果:

 技术分享图片

三、for循环:

代码

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

    for(var index = 0;index<arr.length;index++){

        console.log(arr[index]);

    }

 

输出结果:

技术分享图片

结论: 

forEach 简洁但不可中断。

for in虽然可以用来遍历数组,但是他主要是用来遍历对象的;而且他还会将原型中的方法遍历出来;

for 循环使用于长度已知的操作对象。

 

 

 

逆战班

2020/4/6

 

forEach,for..... in,for循环的区别

原文:https://www.cnblogs.com/miss-vogel/p/12643739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!