当前位置:网站首页>关于for...in和for...of理解和使用
关于for...in和for...of理解和使用
2022-07-21 18:09:00 【益达木咸醇】
因为之前老是遇到这两个都忘记怎么使用,今天就把他们都写下来,给自己留个笔记,也希望能够帮到有需要的朋友。
**
for…in
var arr1 = ["zou", "liu", "chen", "yang", "li", "wu"];
var arr2 = {
"name": "益达",
"age": 24,
"sex": "男",
"birth": "1996-03-06"
};
for (let i in arr2) {
console.log(i);
}
for (let j in arr1) {
console.log(j);
}
结果如下:
由此可以看出,for…in是遍历数组或者对象的下标值,也就是所谓的key值,
倘如你要使用for…in来遍历值(value)的话就要这样:
var arr1 = ["zou", "liu", "chen", "yang", "li", "wu"];
var arr2 = {
"name": "益达",
"age": 24,
"sex": "男",
"birth": "1996-03-06"
};
for (let i in arr2) {
console.log(arr2[i]);
}
for (let j in arr1) {
console.log(arr1[j]);
}
输出:
这里要说下的是一般访问对象的话会用arr2.name这种方式来访问value值,但是在for…in循环里不能用这种方式来访问获取到对应的value值,上图:
var arr2 = {
"name": "益达",
"age": 24,
"sex": "男",
"birth": "1996-03-06"
};
for (let i in arr2) {
console.log(arr2.i);
}
结果是四个undefined,具体原因也不是很清楚,欢迎有知道的朋友下方评论区评论。
总结:如果仅仅只是为了获取key值,那么for…in还是可以使用的
for…of
var arr1 = ["zou", "liu", "chen", "yang", "li", "wu"];
var arr2 = {
"name": "益达",
"age": 24,
"sex": "男",
"birth": "1996-03-06"
};
for (let k of arr1) {
console.log(k);
}
for (let l in arr1) {
console.log(l);
}
结果:
可以看到for…of是可以用来遍历对象或者数组的value值的。
另外这里顺带提一下forEach()这个 方法对数组是每个元素执行一次提供的函数,公因式:数组.forEach(function(数组的value,数组的key,数组本身){…})
forEach按照需要场景使用,这里只是提一下
边栏推荐
- How much do you know about the benefits of encouraging enterprise knowledge sharing?
- 【Datasheet】PHY KSZ9031千兆网络芯片解读
- 微信小程序Text限定行数
- 静态属性,super()
- 生物化学复习题VIII·脂代谢
- Date function of Oracle function Encyclopedia
- Animate the box in the middle and 100px to the left and right of the browser
- 32.二叉树中的最大路径和
- Introduction to wechat applet routing
- PageHelper的使用
猜你喜欢
When packaged in the form of build patches, the client cannot load metadata.
Responsive layout viewport and common units
EAS Web BIM啟動訪問提示500錯誤
[Datasheet] PHY LAN8720网络芯片解读
粘性定位(sticky)详解
数智融合加速驱动企业商业创新
EAS BOS 自定义导出(含Excel样式设置、多页签导出、导出文件目录校验及备份)
Detailed explanation of sticky positioning
无套路、无陷阱、无广告 | 这个免费的即时通讯软件确定不用吗?
Activity启动(launchActivity/startActivity)_(1)_流程图之WMS
随机推荐
Review of Biochemistry VII. Glucose metabolism
[STM32 ]内部独立看门狗IWDG
获取当前年月和之前的11个月份
小程序输出console
EAS 审批流相关表
Kotlin基础语法
微信小程序传参的参数中有问号 识别不了“?”(问号)后面的内容
File read / write operation (files under the specified file directory)
Responsive layout - font common units
Kotlin basic grammar
微信小程序 Image 图片实现宽度100%,高度自适应
NProgress
让盒子居中且距离浏览器左右各100px做动画
MVP_ User login instance 2_ test case
Sqlserver copies tables in a database to another database
微信小程序详解wx:if elif else的用法(搭配view、block)
performance 优化
Thunderbolt interview questions
关于线程 thread (1)概念简介
文字超出部分变成省略号的三种方式