当前位置:网站首页>for...in 和 for...of 的区别
for...in 和 for...of 的区别
2022-07-30 21:45:00 【鱼子酱酱酱】
for…in 和 for…of 的区别
key 和 value
for…in 遍历 key , for…of 遍历 value
const arr = [10, 20, 30]
for (let n of arr) {
console.log(n)
}
const str = 'abc'
for (let s of str) {
console.log(s)
}
function fn() {
for (let argument of arguments) {
console.log(argument) // for...of 可以获取 value ,而 for...in 获取 key
}
}
fn(10, 20, 30)
const pList = document.querySelectorAll('p')
for (let p of pList) {
console.log(p) // for...of 可以获取 value ,而 for...in 获取 key
}
遍历对象
for…in 可以遍历对象,for…of 不可以
遍历 Map/Set
for…of 可以遍历 Map/Set ,for…in 不可以
const set1 = new Set([10, 20, 30])
for (let n of set1) {
console.log(n)
}
let map1 = new Map([
['x', 10], ['y', 20], ['z', 3]
])
for (let n of map1) {
console.log(n)
}
遍历 generator
for…of 可遍历 generator ,for…in 不可以
function* foo(){
yield 10
yield 20
yield 30
}
for (let o of foo()) {
console.log(o)
}
对象的可枚举属性
for…in 遍历一个对象的可枚举属性。
使用 Object.getOwnPropertyDescriptors(obj) 可以获取对象的所有属性描述,看 enumerable: true 来判断该属性是否可枚举。
对象,数组,字符传
可迭代对象
for…of 遍历一个可迭代对象。
其实就是迭代器模式,通过一个 next 方法返回下一个元素。
该对象要实现一个 [Symbol.iterator] 方法,其中返回一个 next 函数,用于返回下一个 value(不是 key)。
可以执行 arr[Symbol.iterator]() 看一下。
JS 中内置迭代器的类型有 StringArrayargumentsNodeListMapSetgenerator 等。
答案
- for…in 遍历一个对象的可枚举属性,如对象、数组、字符串。针对属性,所以获得 key
- for…of 遍历一个可迭代对象,如数组、字符串、Map/Set 。针对一个迭代对象,所以获得 value
题外话:for await…of
用于遍历异步请求的可迭代对象。
// 像定义一个创建 promise 的函数
function createTimeoutPromise(val) {
return new Promise(resolve => {
setTimeout(() => {
resolve(val)
}, 1000)
})
}
如果你明确知道有几个 promise 对象,那直接处理即可
(async function () {
const p1 = createTimeoutPromise(10)
const p2 = createTimeoutPromise(20)
const v1 = await p1
console.log(v1)
const v2 = await p2
console.log(v2)
})()
如果你有一个对象,里面有 N 个 promise 对象,你可以这样处理
(async function () {
const list = [
createTimeoutPromise(10),
createTimeoutPromise(20)
]
// 第一,使用 Promise.all 执行
Promise.all(list).then(res => console.log(res))
// 第二,使用 for await ... of 遍历执行
for await (let p of list) {
console.log(p)
}
// 注意,如果用 for...of 只能遍历出各个 promise 对象,而不能触发 await 执行
})()
【注意】如果你想顺序执行,只能延迟创建 promise 对象,而不能及早创建。
即,你创建了 promise 对象,它就立刻开始执行逻辑。
(async function () {
const v1 = await createTimeoutPromise(10)
console.log(v1)
const v2 = await createTimeoutPromise(20)
console.log(v2)
for (let n of [100, 200]) {
const v = await createTimeoutPromise(n)
console.log('v', v)
}
})()
边栏推荐
- 微信公众号授权登录后报redirect_uri参数错误的问题
- Qt 同时生成动态库和静态库
- C语言犄角旮旯的知识之结构体
- Google Earth Engine ——
- Jetson AGX Orin 平台关于c240000 I2C总线和GMSL ses地址冲突问题
- 牛客网——业务分析-提取值
- 【零代码工具】15 款企业级零代码开发平台推荐,总有一款是你心仪的
- 小心你的字典和样板代码
- 1064 Complete Binary Search Tree
- MySQL 8.0.29 decompressed version installation tutorial (valid for personal testing)
猜你喜欢

面试难题:分布式 Session 实现难点,这篇就够!

LeetCode·Daily Question·952. Calculate Maximum Component Size by Common Factor·Union Check

Uni-app 小程序 App 的广告变现之路:激励视频广告

Navicat new database

CISP-PTE Zhenti Demonstration

MySQL 8.0.29 set and modify the default password

A simple rich text editor

MySQL压缩包方式安装,傻瓜式教学

新书上市 |《谁在掷骰子?》在“不确定性时代”中确定前行

cmd (command line) to operate or connect to the mysql database, and to create databases and tables
随机推荐
navicat无法连接mysql超详细处理方法
navicat新建数据库
socket: Kernel initialization and detailed process of creating streams (files)
不用bs4的原因居然是名字太长?爬取彩票开奖信息
小心你的字典和样板代码
ValueError: Append mode is not supported with xlsxwriter解决方案
Union, the difference between union and structure, the knowledge of enumeration of C language corners
JUC原子类详解
It is enough for MySQL to have this article (disgusting typing 37k words, just for Bojun!!!)
cnpm installation steps
MySQL 用户授权
The structure of knowledge in the corners of the C language
y82.第四章 Prometheus大厂监控体系及实战 -- 监控扩展和prometheus 联邦(十三)
cmd (command line) to operate or connect to the mysql database, and to create databases and tables
史上超强最常用SQL语句大全
NEOVIM下载安装与配置
How do I refresh the company's background management system (Part 1) - performance optimization
Difference between cookie and session
折叠旧版应用程序
kubernetes