×

小结:js中forEach,for in,for of循环

作者:Terry2021.02.26来源:Web前端之家浏览:4276评论:0
关键词:js

小结:js中forEach,for in,for of循环。

一般的遍历数组的方法:

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

用for in的方遍历数组,得到的是索引:

var array = [1,2,3,4,5,6,7];
for(let index in array) {
  console.log(index,array[index]);
};

forEach,得到的是元素

var array = [1,2,3,4,5,6,7];
 
array.forEach(e=>{
  console.log(e);
});
 
array.forEach(function(e){
  console.log(e);
});

用for in不仅可以对数组,也可以对enumerable对象操作!得到的是索引

var table = {
  a : 10,
  b : true,
  c : "jadeshu"
};
 
for(let index in table) {
  console.log(index, table[index]);
}

在ES6中,增加了一个for of循环,得到的是元素

var array = [1,2,3,4,5,6,7];
 
for(let ele of array) {
  console.log(ele);
};
 
var str = "helloabc";
for(let ele of str) {
  console.log(ele);
}

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js20210226a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: