๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐Ÿ–ฅ dev-ruby

[์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ] ๊ฐ์ฒด(Object) ๋ฐ˜๋ณต๋ฌธ ๋Œ๋ฆฌ๋Š” ๋ฒ• ๋ณธ๋ฌธ

javascript

[์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ] ๊ฐ์ฒด(Object) ๋ฐ˜๋ณต๋ฌธ ๋Œ๋ฆฌ๋Š” ๋ฒ•

ruby_s 2022. 1. 25. 13:18
728x90
๋ฐ˜์‘ํ˜•
SMALL

for...in ๋ฌธ, for...of ๋ฌธ

for...in

for...in ๋ฌธ์€ ๊ฐ์ฒด์˜ key๋ฅผ ํ•˜๋‚˜์”ฉ ๊ฐ€์ ธ์˜จ๋‹ค.

const obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}

for (const key in obj) {
  console.log(obj[key]);
}

// value1
// value2
// value3

for...of

for...of ๋ฌธ์€ iterableํ•œ ์†์„ฑ์„ ์ง€๋‹Œ String, Array, TypedArray, Map, Set์—์„œ ๊ฐ’์„ ํ•˜๋‚˜์”ฉ ๊ฐ€์ ธ์˜จ๋‹ค.
๊ฐ์ฒด๋Š” iterable์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.
๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— 
Object.keys(object) ํ˜น์€ Object.values(object)๋ฅผ ํ†ตํ•ด ๋ฐฐ์—ด๋กœ ๋ฐ”๊ฟ”์„œ ๊ฐ’์„ ๊ฐ€์ ธ์™€์•ผ ํ•œ๋‹ค.
Object.entries(object)๋ฅผ ์ด์šฉํ•˜๋ฉด enumerable ์†์„ฑ์˜ key์™€ value ๋ฐฐ์—ด์„ ๋™์‹œ์— ๊ฐ€์ ธ์˜ฌ ์ˆ˜๋„ ์žˆ๋‹ค.

const obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}

for (const value of obj) { // TypeError: obj is not iterable
  console.log(value);
}

for (const key of Object.keys(obj)) {
  console.log(key);
}

// key1
// key2
// key3

for (const value of Object.values(obj)) {
  console.log(value);
}

// value1
// value2
// value3

for (const [key, value] of Object.entries(obj)) {
  console.log(key + ': ' + value);
}

// key1: value1
// key2: value2
// key3: value3

 

 

728x90
๋ฐ˜์‘ํ˜•
LIST