一、遍历数组
使用for…in 会遍历数组元素下标
let items = ['alex', 18,'boy']
for(let item in items){
console.log(item) //数组元素下标
}
可通过数组元素下标获取对应元素
for(let item in items){
console.log(item+":"+items[item])
}
使用for…of 可遍历数组元素
for(let item of items){
console.log(item)
}
二、遍历对象
使用for…in 会遍历对象属性名
let obj = {name:'alex',age : 18,sex : 'boy'}
for(let item in obj){
console.log(item) //对象属性名
}
可通过对象属性名获取对应的属性值
for(let item in obj){
console.log(item+":"+obj[item])
}
使用for…of 会报错
for(let item of obj){
console.log(item)
}
三、遍历字符串
使用for…in 会遍历字符串中字符下标
let str = '23123';
for(item in str){
console.log(item) //字符串中字符下标
}
使用for…of 可遍历字符串中字符
for(item of str){
console.log(item) //字符串中字符
}