for in
和 for of
The differences and similarities
To compare | for in |
for of |
---|---|---|
The difference between | You can iterate over normal objects Iterates through the prototype object of the array You can iterate through the array itself The value that I’m going to iterate over is 0 key It is not traversable map/set You can’t iterate generators Internet explorer support |
Normal objects cannot be traversed It doesn’t iterate through the prototype object It doesn’t iterate over its own properties The value that I’m going to iterate over is 0 value Can traverse map/set To iterate generators IE does not support |
The same | You can iterate through groups of numbers can break Interrupt traversal |
You can iterate through groups of numbers can break Interrupt traversal |
- The sample
const obj = {
a: 1.b: 2.c: 3.d: 4.e: 5
}
const arr1 = [1.2.3.4.5.6.7.8]
for (let i in obj) {
console.log('for in break before', i, obj[i])
if (obj[i] > 3) {
break
}
console.log('for in break after', i, obj[i])
}
console.log('-- -- -- -- -- -)
for (let i of arr1) {
console.log('for of break before', i)
if (i > 3) {
break
}
console.log('for of break after', i)
}
Copy the code