当前位置:网站首页>5.for in 和 for of区别和使用
5.for in 和 for of区别和使用
2022-07-31 08:39:00 【道长道长IOT】
直接上代码,有注释,有内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const arr = ['goods',2,3,4,5,'a','b']
for(let item in arr){
console.log(item);
}
// for in 遍历的是数组的下标,也就是他的索引值,这里打印的结果就是0,1,2,3,4,5,6
// 所以说其实for in 不适合于数组的遍历,他更适合于遍历普通的对象、同时for in 还可以拿到原型链上的对象
const obj = {
name: '何志伟',
age: 18,
}
for (let inkey in obj){
console.log('in对象---' + inkey);
// 这里打印name,age
console.log(obj[inkey]);
// 这里打印的是 何志伟 18
}
// for of 更适合于遍历一个数组,他会打印里面所有的值
for(let ofkey of arr){
console.log('of-----数组-' + ofkey);
// 这里打印'goods',2,3,4,5,'a','b'
}
// 也可以使用for of 获得对象的属性
let obj2 = {
name:"张三", age:25, address:"深圳", getName:function(){
} }
for(let ofKey of Object.keys(obj2)){
console.log(ofKey);
}
</script>
</body>
</html>
边栏推荐
- 【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符
- 关于Error EPERM operation not permitted, mkdir...几种解决办法的比较
- 【C#】说说 C# 9 新特性的实际运用
- 傅里叶变换,拉普拉斯变换学习记录
- 利用frp服务器进行内网穿透ssh访问
- I advise those juniors and juniors who have just started working: If you want to enter a big factory, you must master these core skills!Complete Learning Route!
- How on one machine (Windows) to install two MYSQL database
- 【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
- Define event types in Splunk Web
- 文件的逻辑结构与物理结构的对比与区别
猜你喜欢
随机推荐
Small application project development, jingdong mall 】 【 uni - app custom search component (below) - search history
《如何戒掉坏习惯》读书笔记
Vulkan与OpenGL对比——Vulkan的全新渲染架构
Flutter Paystack implements all options
WLAN部署(AC+AP)配置及常见问题记录
How on one machine (Windows) to install two MYSQL database
Kotlin 优点
SQL语句知识大全
Modular specifications
【问题记录】TypeError: eval() arg 1 must be a string, bytes or code object
The torch distributed training
[MySQL exercises] Chapter 2 Basic operations of databases and data tables
@RequestBody和@RequestParam区别
How to Install MySQL on Linux
深度理解递归,手撕经典递归问题(汉诺塔,青蛙跳台阶),保姆级教学。
torch分布式训练
免安装版的Mysql安装与配置——详细教程
【云原生&微服务五】Ribbon负载均衡策略之随机ThreadLocalRandom
功能强大的国产Api管理工具
手写promise