一:for in 的使用
for in 常用遍历对象,当然,也可以遍历数组,但二者遍历的结果还是有所不同
代码区 :
一:for in 数组遍历的使用
var arr = [3, 4, 5, 6, 7, 8];
for (let i in arr) {
console.log(typeof(i), i);
console.log(arr[i]);
}
在数组中,输出结果typeof[i],i,arr[i]结果为:
string 0
3
string 1
4
string 2
5
string 3
6
string 4
7
string 5
8
总结for in在数组输出结果
1.首先输出typeof[i]的类型为string
2.输出数组i的值为索引号(下标号),从0开始的字符型
3.arr[i]返回的是键值,即数组的值
二:for in对象遍历的使用
代码区:
var Obj = {
temp: 'rng',
name1: 'Xiaohu',
name2: 'Wei',
name3: 'Cryin',
name4: 'Gala',
name5: 'Ming'
}
var tempPersonName = ''
for (let i in Obj) {
console.log(i);
tempPersonName = Obj[i] != 'Ming' ? tempPersonName + Obj[i] + '和' : tempPersonName = tempPersonName + Obj[i];
}
console.log(tempPersonName);
输出i结果分别为:
temp
name1
name2
name3
name4
name5
输出tempPersonName结果为:
rng和Xiaohu和Wei和Cryin和Gala和Ming
总结for in在对象输出结果
1.i返回的是键名,即对象属性
2.属性值(键值)可以以数组的形式输出,例如Obj[i]
二:for of的使用
1.for of 通常只用于数组的遍历
代码区 :
var arr = [3, 4, 5, 6, 7, 8];
for (let i of arr) {
console.log(typeof(i), i);
}
在数组中,输出结果typeof[i],i结果为:
number 3
number 4
number 5
number 6
number 7
number 8
总结for of在数组输出结果
1.首先输出typeof[i]的类型为number
2.输出i的值为数组值
2.for of不可直接用于对象的遍历
代码区 :
var Obj = {
temp: 'rng',
name1: 'Xiaohu',
name2: 'Wei',
name3: 'Cryin',
name4: 'Gala',
name5: 'Ming'
}
var tempPersonName = ''
for (let i of Obj) {
tempPersonName = Obj[i] != 'Ming' ? tempPersonName + Obj[i] + '和' : tempPersonName = tempPersonName + Obj[i];
}
console.log(tempPersonName);
输出结果tempPersonName为:
Uncaught TypeError: Obj is not iterable
可见结果报错
总结for of在对象输出结果
1.for of不可直接用于对象的遍历!