- for …in 遍历 键名;遍历对象的整个原型链,性能差
数组不太适用!
// 遍历对象 i 是 key, a 是 对象本身
let a = {name: 'zs', age: 18, sex: 'man'};
for(let i in a) {
console.log(i + '---' + a[i])
} // name---zs age---18 sex---man
// 遍历数组 不建议不建议不建议
let a = [1, 3, 5, 7, 9];
for(let i in a) {
console.log(i + '---' + a[i])
}// 0---1 1---3 2---5...
- for…of ES6的语法;遍历 键值;只遍历对象本身
对象不太适用!!!!!
// 遍历数组
let a = [1, 3, 5, 7, 9];
for(let i of a) {
console.log(i)
}// 1 3 5 7 9
// 遍历字符串
let a = 'qwer';
for(let i of a) {
console.log(i)
}// q w e r
// 也可以遍历 Set类型数据
let a = [1, 3, 5, 7, 9];
let b = new Set(a);
for(let i of b) {
console.log(i, b)
}// 1 3 5 7 9
总结就是: for…in适合遍历对象; for…of适合遍历数组(类数组)
909

被折叠的 条评论
为什么被折叠?



