当前位置:网站首页>ES6中的for...in/of的使用
ES6中的for...in/of的使用
2022-08-10 20:31:00 【Matcha_ice_cream】
下面以对象和数组为例,介绍一下for…in,for…of以及基本for循环的使用
for…of: 遍历的对象必须是可迭代的对象
可迭代的对象包括: Array,Set,Map,DOM中的NodeList对象,String对象,函数的arguments属性
1、在数组中
ES5中的for循环,正常遍历中 i 指的是数组的下标
ES6中,for…in循环,遍历中的 i 指的是数组的下标
ES6中,for…of循环,遍历中的 i 指的是数组中的值
代码展示:
let arr = [1, 3, 5, 7, 9];
for(let i = 0; i < arr.length; i++) {
console.log('for循环中i是数组的下标:', i);
console.log('arr[i]是数组中的值:', arr[i]);
}
console.log('----------------------------');
for(let i in arr) {
console.log('for...in中i是数组的下标:', i);
}
console.log('----------------------------');
for(let i of arr) {
console.log('for...of中i是数组中的值', i)
}
显示效果:
2、在对象中
不能使用 for…of 遍历对象,因为它不是一个可迭代的对象。
代码展示:
let obj = {
name: "YiBo",
age: 18
}
for(let i in obj) {
console.log('for...in循环中的i值得是对象的键', i);
}
console.log('------------------------------------');
for(let i of obj) {
console.log(i);
}
显示效果:
边栏推荐
- 如何提高代码的可读性 学习笔记
- Heme - gold nanoparticles (Heme - AuNP) composite nanometer enzyme | gold nanoparticles nuclear porous hollow carbon nanometer spherical shell (Au @ HCNs) nano enzyme
- 链表应用----约瑟夫问题
- Auto.js中的悬浮窗
- LeetCode 1-10题
- Tf ferritin particles contain cisplatin / oxaliplatin / doxorubicin / methotrexate MTX / paclitaxel PTX and other drugs
- Public Key Retrieval is not allowed(不允许公钥检索)【解决办法】
- leetcode 547.省份数量 并查集
- svg+元素js实现在图片上描点成框,并获取相对图片的坐标位置
- MySQL查询数据库中的表和字段
猜你喜欢
随机推荐
Are you hungry - Institution tree radio
机器学习笔记:t-SNE
C 语言 时间函数使用技巧(汇总)
知识图谱Knowledge Graph
2021 GKCTF X DASCTF应急挑战杯
Common functions of Auto.js to find pictures and colors
npm‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件
Iridium Ruthenium Alloy/Iridium Oxide Biomimetic Nanozyme | Palladium Nanozyme | GMP-Pd Nanozyme | Gold-Palladium Composite Nanozyme | Ternary Metal Pd-M-Ir Nanozyme |shell nanozyme
Multifunctional Nanozyme Ag/PANI | Flexible Substrate Nano ZnO Enzyme | Rhodium Sheet Nanozyme | Ag-Rh Alloy Nanoparticle Nanozyme | Iridium Ruthenium Alloy/Iridium Oxide Biomimetic Nanozyme
(十)图像数据的序列与反序列化
报错:runtime error: reference binding to null pointer of type ‘std::vector<int, std::allocator<int>>‘
如何提高代码的可读性 学习笔记
【CMU博士论文】视频多模态学习:探索模型和任务复杂性,152页pdf
【ACM】dp专场训练
导入FontForge生成字体
Auto.js中的悬浮窗
2019河北省大学生程序设计竞赛部分题题解
参天生长大模型:昇腾AI如何强壮模型开发与创新之根?
ansible各个模块的详解和使用
【go】依赖注入