ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ


for ... of ๊ตฌ๋ฌธ์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ธฐ๋ณธ์ ์ธ MDN์˜ ์ •์˜๋Š” ์ด๋Ÿฌํ•ฉ๋‹ˆ๋‹ค.


for...of ๋ฌธ(statement)์€ ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด (ArrayMapSetStringTypedArrayarguments ๊ฐ์ฒด ๋“ฑ์„ ํฌํ•จ)์— ๋Œ€ํ•ด์„œ ๋ฐ˜๋ณตํ•˜๊ณ  ๊ฐ ๊ฐœ๋ณ„ ์†์„ฑ๊ฐ’์— ๋Œ€ํ•ด ์‹คํ–‰๋˜๋Š” ๋ฌธ์ด ์žˆ๋Š” ์‚ฌ์šฉ์ž ์ •์˜ ๋ฐ˜๋ณต ํ›„ํฌ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฃจํ”„๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.


๋ณดํ†ต for ...of๋ฌธ์€ for ...in๋ฌธ๊ณผ ๋น„๊ต๋ฅผ ํ•˜๊ณค ํ•˜๋Š”๋ฐ ์ค‘์š”ํ•œ ์ฐจ์ด์  ํ•˜๋‚˜๋งŒ ์งš๊ณ  ๋„˜์–ด๊ฐ€๊ฒ ์Šต๋‹ˆ๋‹ค.


let info = {
	'name' : 'Lee',
	'age' : 28,
	'sex' : 'm'
}

for(let i in info){
	console.log(i);		//name age sex
}
for(let i of info) {
       console.log(i);          //TypeError: info is not iterable
}

for in๋ฌธ์€ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ์†์„ฑ์˜ ๊ฐ์ฒด๊ฐ€ ์•„๋‹์ง€๋ผ๋„ ๋ชจ๋“  ์—ด๊ฑฐ ๊ฐ€๋Šฅํ•œ ์†์„ฑ์„ ๊ฐ€์ง„ ๊ฐ์ฒด์— ๋Œ€ํ•ด ๋ฐ˜๋ณต์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ for...of ๊ตฌ๋ฌธ์€ [Symbol.iterator] ์†์„ฑ์„ ๊ฐ€์ง€๋Š” ์ปฌ๋ ‰์…˜๋งŒ์ด ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ๊ตฌ๋ฌธ์ž…๋‹ˆ๋‹ค. ์—๋Ÿฌ์—์„œ๋„ not iterable ์ด๋ผ๊ณ ํ•ด์„œ ๋ฐ˜๋ณต์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋ผ๊ณ  ์•Œ๋ ค์ฃผ๊ณ  ์žˆ์ฃ . Symbol์€ ES6์—์„œ ๋“ฑ์žฅํ•œ ์ž๋ฃŒํ˜•์œผ๋กœ ์•„์ง ํฌ์ŠคํŒ…ํ•˜์ง€๋Š” ์•Š์•˜๋Š”๋ฐ ์—„์ฒญ ์ค‘์š”ํ•˜๊ฒŒ ์ƒ๊ฐํ•˜์ง„ ์•Š์œผ์…”๋„ ๋˜๊ฒ ์Šต๋‹ˆ๋‹ค.


let str = "korea";

for(let i in str) { console.log(i)}	//0 1 2 3 4
for(let i of str) { console.log(i)}	//k o r e a

MDN์˜ ์ •์˜์—์„œ๋„ ๋งํ–ˆ๋‹ค์‹œํ”ผ for...of๋ฌธ์€ ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด์— ๋Œ€ํ•ด์„œ ์‹คํ–‰๋˜๋Š” ๋ฐ˜๋ณต๋ฌธ์ด๋ฉด์„œ ๊ฐœ๋ณ„ ์†์„ฑ๊ฐ’์— ๋Œ€ํ•ด ์‹คํ–‰๋˜๋Š” ๊ตฌ๋ฌธ์ž…๋‹ˆ๋‹ค. ๊ทธ์—๋ฐ˜ํ•ด for in์€ ๊ฐ’์ด ์•„๋‹Œ key ์— ์ดˆ์ ์„ ๋งž์ถ”๊ณ  ์žˆ์ฃ . 



๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋Š” ๋ถ€๋ถ„์—์„œ ๋˜ ํ•˜๋‚˜์˜ ์˜ˆ์‹œ๋ฅผ ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.


let iterable = [3,5,7];
iterable.notIterable = "not iterable";

for(let i in iterable){
	console.log(i);		//0 1 2 notIterable
}

for(let i of iterable){
	console.log(i);		//3 5 7
}


๋ณด์‹œ๋‹ค์‹œํ”ผ iterable ๊ฐ์ฒด์— notIterable ํ‚ค๋ฅผ ๊ฐ€์ง€๋Š” ๊ฐ์ฒด๋ฅผ ํ•˜๋‚˜ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทผ๋ฐ for in๋ฌธ์—์„œ๋Š” key๊ฐ€ ์ถœ๋ ฅ์ด ๋˜์—ˆ๋Š”๋ฐ for of ๋ฌธ์—์„œ๋Š” ํ‚ค ๊ฐ’์ด ์ถœ๋ ฅ์ด ์•ˆ๋๋‹ค๋Š” ๊ฒƒ์€ {"notIterable : "not iterable" } ํ˜•ํƒœ๋กœ ์ถ”๊ฐ€๋œ ์ด ๊ฐ์ฒด๋Š” iterableํ•œ ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๋ผ๋Š” ๋œป์ž…๋‹ˆ๋‹ค. ์ฒ ์ €ํ•˜๊ฒŒ iterable ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด์— ๋Œ€ํ•ด์„œ๋งŒ ๊ฐ’์„ ์ถœ๋ ฅํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์ฃ .

'javascript > ๋ชจ๋˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[javascript] - Promise bulk๋กœ ์ฒ˜๋ฆฌํ•˜๊ธฐ  (0) 2023.02.10
9. generators  (0) 2019.01.22
7. let + const  (0) 2019.01.06
6. default + rest + spread  (0) 2019.01.03
5. destructuring  (0) 2018.12.31
๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
ยซ   2025/01   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ