fetch(
'https://api.themoviedb.org/3/movie/top_rated?api_key=5e19d720d8a39386697259e7163ef8bc&language=ko-KR&page=1',
options
)
.then((response) => response.json())
.then((data) => console.log(data))
api ์์ ๋ฐ์์จ ๋ฐ์ดํฐ๋ฅผ ์ฝ์๋ก ์ถ๋ ฅ
๋ฐ์์จ ๋ฐ์ดํฐ์ result๋ 20๊ฐ์ ๋ฐฐ์ด๋ก ์ด๋ฃจ์ด์ ธ ์๊ณ , ํ๋ํ๋์ ์์๋ ๊ฐ์ฒด๋ก ๊ตฌ์ฑ์ด ๋์ด์๋ค.
results ๊ฐ์ ์์๋ง๋ค ์ ๋ฐ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง๊ณ ์๊ณ ,
๊ฐ ์์๋ ์ด๋ฌํ key-value๋ก ๊ตฌ์ฑ์ด ๋์ด์๋ค.
์ฌ๊ธฐ์ ํ๋ํ๋ ์์์ title ๊ฐ์ธ ์ ๋ชฉ์ ์ ๊ทผ์ ํด์ ์ํ ์ ๋ชฉ๋ค๋ง ๊ฐ์ง๊ณ ์ค๋ ์ฝ๋๋ฅผ ๋๋ ํ์คํ ์๊ณ ์์๋ค ์๊ฐํ์ผ๋,
ํญ์ ์ต๊ด์ ์ผ๋ก ๋ฐฐ์ด์ ๋ณด๋ฉด forEach๋ฅผ ๋๋ ค์จ ํ์, ํ๋ ๊ฐ๊ณผํ ๋ถ๋ถ์ด ์์๋ค.
fetch(
'https://api.themoviedb.org/3/movie/top_rated?api_key=5e19d720d8a39386697259e7163ef8bc&language=ko-KR&page=1',
options
)
.then((response) => response.json())
.then((data) => console.log(data.result))
์ด๋ ๊ฒ ๋ฐ์ดํฐ์ results ๊ฐ์ ์ ๊ทผ์ ํ๊ณ ,
fetch(
'https://api.themoviedb.org/3/movie/top_rated?api_key=5e19d720d8a39386697259e7163ef8bc&language=ko-KR&page=1',
options
)
.then((response) => response.json())
.then((data) => console.log(data.results.title))
์ด๋ ๊ฒ ๋ฐ๋ก title ๊ฐ์ ์ ๊ทผ์ ํ๋๋...
๋ ์ด ์ํฉ์ ์ดํดํ ์๊ฐ ์์๋ค.
"์๋ ๊ฐ์ผ๋ฉด 20๊ฐ์ ์ํ ์ ๋ชฉ๋ค์ด ์ฃผ๋ฃจ๋ฃฉ ๋์์ผ ํ๋๋ฐ,..?? ์ undefined(= ๊ฐ์ด ์์) ์ด๋ผ๊ณ ๋์ฌ๊น..?"
fetch(
'https://api.themoviedb.org/3/movie/top_rated?api_key=5e19d720d8a39386697259e7163ef8bc&language=ko-KR&page=1',
options
)
.then((response) => response.json())
.then((data) => {
let rows = data.results;
rows.forEach((a) => {
console.log(a.title);
});
})
๊ทธ๋์ ์ด๋ฒ์ ํญ์ ์ฑ๊ณต์ ์ผ๋ก ๊ฒฐ๊ณผ๊ฐ์ ์ถ๋ ฅํ๋ ์ฝ๋์ธ forEach ๋ฅผ ์จ์ ๋ค์ ์๋ํด ๋ณด์๋ค.
์ ๋์ค๋๋ฐ... ์ ์๊น๋ undefined๊ฐ ๋์๋ ๊ฑฐ์ง? ๋ผ๊ณ ์๊ฐ์ ํ๊ณ ์ด๊ฒ์ ๊ฒ console.log()๋ฅผ ์ฐ์ด๋ณด๊ณ ๋์์ผ ์์๋ค.
forEach ๊ฐ ์ ๋ ๊ฒ ์ ์์ ์ผ๋ก ๋ด๊ฐ ์ํ๋ ๋ฐ์ดํฐ๋ฅผ ๋ฝ์์ ๊ฐ์ ธ์ค๋ ์ด์ ๋,
1. data์ results ๊ฐ์ rows ๋ผ๊ณ ์ ์ธ์ ํ๊ณ
2. rows ์ ๋ฐฐ์ด ์์๋ค์ด a๋ผ๋ ๋งค๊ฐ๋ณ์ ์์ผ๋ก "ํ ์์์ฉ" ๋ค์ด์ค๋ฉด์ ๊ทธ ํ ์์๋ง์ title๊ฐ์ a.title๋ก ๊ฐ์ ธ์ค๊ธฐ ๋๋ฌธ์,
3. rows์ ๋ฐฐ์ด ๊ธธ์ด๋งํผ console.log๋ก ์ฐํ๋ฉด์ ์ ์์ ์ผ๋ก a.title์ ๊ฐ์ ๋ฐ๋ณต์ ์ผ๋ก ๋ฝ์ ์๋๊ฒ์ด๊ณ .
๋งจ์ฒ์ ๋ด๊ฐ ์ป๋ console.log(data.results.title)์ด undefined๋ผ๊ณ ๋์๋ ์ด์ ๋,
1. data์ results ๊ฐ์๋ ์ ๊ทผ์ ํ์ผ๋,
2. results ๋ ํ๋์ ์์๊ฐ ๊ฐ์ฒด๋ก ์ด๋ฃจ์ด์ง "๋ฐฐ์ด"์ด์๊ณ ,
3. ๋ฐฐ์ด์ ์ ๊ทผํ๋ [index] ๋ฐฉ์์ ์ฐ์ง์์์ฑ ๊ทธ๋ฅ title์ ์ฝ์๋ก ์ฐ์ด! ๋ผ๊ณ ๋ช ๋ น ํ๋๊น,
4. ๊ฒฐ๊ณผ๊ฐ์ด undefined๊ฐ ๋์ฌ ์ ๋ฐ์ ์๋ ๊ฑฐ์๋ค.
์ค๋ ์ด undefined๋ ๊ฐ์ธ์ ์ผ๋ก ๋์๊ฒ ํฐ ์ถฉ๊ฒฉ์ด์๋ค.
ํญ์ ๋ฐฐ์ด์ ๋ณด๋ฉด ๊ฒฐ๊ณผ๊ฐ์ ๋ฝ์๋ด๊ธฐ ์ํด forEach๋ฅผ ์ฌ์ฉํด ์๋ ๋ฒ๋ฆ์ด ์ด ๋ถ๋ถ์ ๋๋ก์จ ๊ฐ๊ณผํ๊ฒ ๋ง๋ค์๊ธฐ ๋๋ฌธ์ด๋ค.
๋น์ฐํ ์ด๋ฌ๋ฉด ์ฐํ๊ฒ ์ง๋ผ๊ณ ๋ง์์์ผ๋ก ์๊ฐํ๋ ๋ถ๋ถ์ด์๊ณ , ์ด๋ก์จ ์กฐ๊ธ ๋ ์ ํํ๊ฒ ๊ฐ๋ ์ ์๋ฏธ๋ฅผ ํ์ ํ์ง ์์๋ ์ถ์ ๋ง์์ด๋ค.
#forEach #๋ฐฐ์ด์ ๊ทผ #์ต๊ด #undefined