当前位置:网站首页>关于 for in与for of 的差别以及如何使用
关于 for in与for of 的差别以及如何使用
2022-08-04 05:26:00 【strongest强】
一: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不可直接用于对象的遍历!
三:结束语
感谢大家的观看,你们的点赞和收藏,是对作者最大的支持!
边栏推荐
猜你喜欢
随机推荐
MySQL日志篇,MySQL日志之binlog日志,binlog日志详解
想低成本保障软件安全?5大安全任务值得考虑
显式调用类的构造函数(而不是用赋值构造),实现一个new操作
Can‘t connect to MySQL server on ‘localhost3306‘ (10061) 简洁明了的解决方法
7.18 Day23 - the markup language
8大软件供应链攻击事件概述
一个对象引用的思考
FLV格式详解
力扣:70. 爬楼梯
3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
JS basics - forced type conversion (error-prone, self-use)
Redis common interview questions
4.2 Declarative Transaction Concept
手把手教你实现buffer(二)——内存管理及移动语义
Linux环境下redis的下载、安装和启动(建议收藏)
如何将 DevSecOps 引入企业?
MySQL数据库(基础)
ORACLE LINUX 6.5 安装重启后Kernel panic - not syncing : Fatal exception
MySQL log articles, binlog log of MySQL log, detailed explanation of binlog log
【问题解决】同一机器上Flask部署TensorRT报错记录