JS - for in 和 for of 的遍历顺序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS - for in 和 for of 的遍历顺序相关的知识,希望对你有一定的参考价值。

参考技术A

在 ECMA-262 中没有明确规定此行为,只说取决于实现。现在的普遍实现是先把当中的非负整数键提出来,排序好输出,然后将剩下的按定义时的顺序输出。

参考
for in 循环的输出顺序问题 - 司徒正美 - 博客园

对Set和Map,for of 遍历的顺序是按照各个成员被添加进数据结构的顺序。

参考
Iterator 和 for...of 循环 - ECMAScript 6入门

前端js的数组的循环遍历 for / for of / for in / arr.forEach()

数组的作用是使用单独的变量名来存储一系列的值。数组的功能强大很 ,其方法也很多...

数组的循环遍历 for / for of / for in / arr.forEach()

for 循环
最简单的一种,也是最灵活的
let arr=[1,2,3];
for(let y=0;y<arr.lngth;y++){
console.log(arr[y])
}

for of
//在循环中 let 的 item 就是遍历了的值 他可以更好的方便我们书写代码
let arr=[1,2,3];
for(let item of arr){
console.log(item)
}

for in
//在循环中 let 的 index 为下标 ,和 for of 一样,更简洁的数组遍历方法
for(let index in arr){
console.log(arr[index])
}

arr.forEach()

arr.forEach()//==
arr.forEach(callback)//==
arr.forEach(function(item,index){//item 是元素,index 从零开始,可以表示为数组的下标
console.log(item);//元素
console.log(index);//下标
})
//可以拿到数组的下标和元素
//没返回值

//输出数组内的数字相加的和
例子 for of / arr.forEach

let arr = [1, 4, 34, 23, 4, 8, 12, 7], sum = 0, sum1 = 0;
for (let item of arr) {
sum += item
}
console.log(sum);//93

arr.forEach(function (item) {
sum1 += item
})

console.log(sum1);//93

以上是关于JS - for in 和 for of 的遍历顺序的主要内容,如果未能解决你的问题,请参考以下文章

Js中for in 和for of的区别

JS中的forEach,for in,for of和for的遍历优缺点及区别

JS中的forEach,for in,for of和for的遍历优缺点及区别

js遍历集和(Array,Map,Set) (forEach, map, for, for...in, for...of)

js的forEach,for in , for of

ES6: for...of VS for...in