for in, for of detailed explanation

for in

Can be used in enumerable data => objects

enumerable data

property descriptor => enumerable

example

1. It can be used to traverse objects => attribute name,
such as:
insert image description here
there is an enumerable attribute above, which is to control whether the attribute can be enumerated

Also enumerates the enumerable property names on the object prototype

let obj = {
    
    
    name: "lihegui",
    gender: "nan",
    age: "22"
}
for (let item in obj) {
    
    
    console.log(item);
}
//	name
//	gender
//	age

2. It can be used to traverse the array => array subscript

let arr = ["lihegui", "fxp", "shuzu"]
for (let item in arr) {
    
    
    console.log(item);
}
//	0
//	1
//	2

3. Traverse the string => the subscript of the position of the character

let str = "lihegui"
for (let item in str) {
    
    
    console.log(item);
}
//	0
//	1
//	2
//	3
//	4
//	5
//	6

for of

Can be used in iterable data => array, string, Map, Set

for in traversal map set will be undefined

iterable data

As long as a data implements the Iterator interface, the data will have a property called [Symbol.iterator].
For example, an array has a Synbol.iterator property.

example

1. Traverse the array => each item of the array

let arr = ["lihegui", ["and", "lihegui"], "fxp", "shuzu"]
for (let item of arr) {
    
    
    console.log(item);
}
//	lihegui
//	['and','lihegui']
//	fxp
//	shuzu

2. Traverse the string => each character

let str = "lihegui"
for (let item of str) {
    
    
    console.log(item);
}
//	l
//	i
//	h
//	e
//	g
//	u
//	i

3. Traverse map => each item

let map = new Map([
    [1, 'one'],
    [2, 'two'],
    [3, 'three']
])
for (let item of map) {
    
    
    console.log(item);
}
//	[ 1, 'one' ]
//	[ 2, 'two' ]
//	[ 3, 'three' ]

4. Traverse set => each item

let set = new Set(["lihegui", "fxp"])
for (let item of set) {
    
    
    console.log(item);
}
//	lihegui
//	fxp

Guess you like

Origin blog.csdn.net/qq_45859670/article/details/127042208