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

๊ทธ๋ƒฅ ๊ถ๊ธˆํ•ด์„œ ํ•ด๋ณธ Array empty ์š”์†Œ ์ˆœํšŒ ๊ธฐ๋ก

 

0. ๋นˆ ์š”์†Œ๊ฐ€ ์žˆ๋Š” Array ์ƒ์„ฑ

var arr = [ 1, 2, 3 ];
arr[10] = "last";

console.log(arr);

 

1. for

for( let i=0; i<arr.length; i++ ){
    console.log(`arr[${i}] : ${arr[i]}`);
}

 

2. forEach : Array.prototype.forEach()

forEach๋Š” Array์˜ ํ”„๋กœํ† ํƒ€์ž… ๋ฉ”์†Œ๋“œ์ด๋‹ค. (์–˜๋Š” ๋ฐ˜๋ณต๋ฌธ์ด ์•„๋‹ˆ๋ผ ํ•จ์ˆ˜์ž„)
์ธ์ž๋กœ ๋ฐ›์€ ์ฝœ๋ฐฑํ•จ์ˆ˜๋ฅผ ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ์— ์ ์šฉํ•œ๋‹ค.

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
์ฝœ๋ฐฑํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ์ˆœ์„œ ์ค‘์š”!

arr.forEach( (v, i) => 
    console.log(`arr[${i}] : ${v}`);
);

empty ์š”์†Œ๋Š” ์ˆœํšŒํ•˜์ง€ ์•Š์Œ

 

3. for of : for...of ๋ช…๋ น๋ฌธ

for ... of ๋ช…๋ น๋ฌธ์€ ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด (Array, Map, Set, String, TypedArray, arguments ๊ฐ์ฒด ๋“ฑ์„ ํฌํ•จ)์— ๋Œ€ํ•ด์„œ ๋ฐ˜๋ณตํ•˜๊ณ  ๊ฐ ๊ฐœ๋ณ„ ์†์„ฑ๊ฐ’์— ๋Œ€ํ•ด ์‹คํ–‰๋˜๋Š” ๋ฌธ์ด ์žˆ๋Š” ์‚ฌ์šฉ์ž ์ •์˜ ๋ฐ˜๋ณต ํ›„ํฌ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฃจํ”„๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
๋ชจ๋“  ๊ฐ์ฒด๋ณด๋‹ค๋Š”, [Symbol.iterator] ์†์„ฑ์ด ์žˆ๋Š” ๋ชจ๋“  ์ปฌ๋ ‰์…˜ ์š”์†Œ์— ๋Œ€ํ•ด ์ด ๋ฐฉ์‹์œผ๋กœ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
forEach() ๊ตฌ๋ฌธ๊ณผ ๋‹ฌ๋ฆฌ, break, continue, ๊ทธ๋ฆฌ๊ณ  return ๊ตฌ๋ฌธ๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
for ( let v of arr ) {
    console.log(v)
}

empty ์š”์†Œ๋„ ์ˆœํšŒํ•จ

 

4. for in : for...in

 !  for ... in ๋ฌธ์˜ ๊ฒฝ์šฐ Array์—์„œ๋Š” ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

๊ทธ ์ด์œ ์ธ ์ฆ‰์Šจ,
์ฒซ์งธ๋กœ index ์ˆœ์„œ๊ฐ€ ๋ณด์žฅ๋˜์ง€ ์•Š์œผ๋ฉฐ,
๋‘˜์งธ๋กœ  arr.owner = "Carrot"  ์ด๋Ÿฐ์‹์œผ๋กœ ํ™•์žฅ ํ”„๋กœํผํ‹ฐ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค๋ฉด ์–˜๋„ ์ˆœํšŒํ•œ๋‹ค.
๊ฑฐ๊ธฐ๋‹ค๊ฐ€ prototype ์ฒด์ธ์„ ํ†ตํ•ด์„œ ๋ฌผ๋ ค๋ฐ›์€ ํ”„๋กœํผํ‹ฐ๋ผ๋„, enumerable ๊ฐ€ true ๋ผ๋ฉด ์ฃ„๋‹ค ์ˆœํšŒํ•œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์–˜๊ฐ€ ์ˆœํšŒํ•˜๋Š” ๊ฑด value ๊ฐ€ ์•„๋‹ˆ๋ผ key ๊ฐ’!

Object์—์„œ๋„ ์–˜๋ณด๋‹จ Object.Keys() ๋ฅผ ์ด์šฉํ•˜๋Š”๊ฒŒ ๋‚ซ๋‹ค๋Š”๋ฐ ์ด๊ฑด ๋‚˜์ค‘์— ์‹œ๊ฐ„๋‚˜๋ฉด ํฌ์ŠคํŒ…ํ• ์ง€๋„..

for ( let key in arr ) {
    console.log(`arr[${key}] : ${arr[key]}`);
}

empty ์š”์†Œ๋Š” ์ˆœํšŒํ•˜์ง€ ์•Š์•˜์ง€๋งŒ ํ™•์žฅ ์š”์†Œ๋Š” ์ถœ๋ ฅ์“ฐ..

 

++ object ์—์„œ์˜ for in ๋ฌธ ์ˆœํšŒ : value๋ฅผ ์ˆœํšŒํ•˜๋ ค๋ฉด obj[key] ํ˜•ํƒœ๋กœ ์ˆœํšŒํ•ด์•ผํ•จ

 

 

๋งˆ์น˜๋ฉฐ

forEach / for of / for in ์˜ ์ฐจ์ด์ ์„ ์ค‘์ ์œผ๋กœ ์“ฐ๋ ค๊ณ  ํ–ˆ๋˜๊ฒŒ ์•„๋‹ˆ์ง€๋งŒ
์“ฐ๋‹ค๋ณด๋‹ˆ ๊ทธ๋ ‡๊ฒŒ ๋˜์—ˆ๋‹ค. (์ฝ”-์“ฑ)

์จŒ๋“  ๋ฐฐ์—ด์˜ empty ์š”์†Œ๋ฅผ ์ˆœํšŒํ•˜๋ ค๋ฉด for, for of ๋ฌธ์„ ์‚ฌ์šฉํ•˜๋Š”๊ฑธ๋กœ ํ•˜์ž.

 

 

์ฝ์„๊ฑฐ๋ฆฌ : https://thecodebarbarian.com/for-vs-for-each-vs-for-in-vs-for-of-in-javascript

http://hacks.mozilla.or.kr/2015/08/es6-in-depth-iterators-and-the-for-of-loop/

๋Œ“๊ธ€