728x90
const animals=[
{name : 'lion' , size:'big', isAggresive: true, weight:200},
{name : 'monkey' , size:'medium', isAggresive: true, weight:20},
{name : 'cat' , size:'small', isAggresive: false, weight:10},
{name : 'rat' , size:'small', isAggresive: false, weight:2},
]
//์ ํต์ ์ธ ๋ฐ๋ณต๋ฌธ
for(let i=0; i<animals.length; i++){
console.log(animals[i]);
}
/*์ถ๋ ฅ๋ฌธ
{name: 'lion', size: 'big', isAggresive: true, weight: 200}
{name: 'monkey', size: 'medium', isAggresive: true, weight: 20}
{name: 'cat', size: 'small', isAggresive: false, weight: 10}
{name: 'rat', size: 'small', isAggresive: false, weight: 2}
*/
//๋ณด๋ค ๊ฐ๊ฒฐํ ๋ฐ๋ณต๋ฌธ
for(let i of animals){
console.log(i)
}
//์์ ์ถ๋ ฅ๋ฌธ๊ณผ ๋์ผ
forEach - ์์์ ์ธ๋ฑ์ค ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
animals.forEach(function(e, index){
console.log(e);
console.log(index);
})
/* ์ถ๋ ฅ๋ฌธ
{name: 'lion', size: 'big', isAggresive: true, weight: 200}
0
{name: 'monkey', size: 'medium', isAggresive: true, weight: 20}
1
{name: 'cat', size: 'small', isAggresive: false, weight: 10}
2
{name: 'rat', size: 'small', isAggresive: false, weight: 2}
3
*/
map : ์ด๋ค ๋ฐฐ์ด์ ๋ค๋ฅธ ํํ์ ๋ฐฐ์ด๋ก ์ฌ์์ฐ
//animal ๊ฐ์ฒด์ name์์ฑ๊ฐ์ผ๋ก ์ด๋ฃจ์ด์ง ๋ฐฐ์ด ์ฌ์์ฐ
const animalsNames = animals.map((e)=> {return e.name})
console.log(animalsNames); // ['lion', 'monkey', 'cat', 'rat']
const animalsNames = animals.map((e)=> {
return `${e.name} size is ${e.size}`;
})
console.log(animalsNames)
/*์ถ๋ ฅ๋ฌธ
['lion size is big',
'monkey size is medium',
'cat size is small',
'rat size is small']
*/
filter : ํน์ ์กฐ๊ฑด์ ๊ฐ์ง ์์๋ง ๋ฝ์๋ด๊ธฐ - ์ค์๊ฐ ๊ฒ์์ด ๊ฐ๋ฅํจ.
const smallAnimals=animals.filter((e)=>{
return e.size === 'small'
})
console.log(smallAnimals);
/*์ถ๋ ฅ๋ฌธ
{name: 'cat', size: 'small', isAggresive: false, weight: 10}
{name: 'rat', size: 'small', isAggresive: false, weight: 2}
*/
reduce : ์ฃผ๋ก ๋ฐฐ์ด์ ํฉ์ ๊ตฌํ ๋ ์ฌ์ฉ (๋ฐฐ์ด์์ ํฉ ๊ตฌํ๊ธฐ)
reduce( ๋์ ๊ฐ, ํ์ฌ๊ฐ, ์ธ๋ฑ์ค, ์์) ํํ์ ๋๋ค.
โป ์ฒซ๋ฒ์งธ ์ธ์๋ ์ด์ ๊ฐ์ด ์๋๋ผ ๋์ ๊ฐ
const numbers=[1,22,333,44,555];
const total=numbers.reduce((acc,cur)=>{
//acc : ๋ํด์ง๊ฐ(๋์ ๊ฐ) / cur : ํ์ฌ๊ฐ
console.log(acc, cur);
return acc + cur;
})
/*์ถ๋ ฅ๋ฌธ
1 22
23 333
356 44
400 555
*/
console.log(total) //955
๋ฐฐ์ด์ ๊ฐ์ฒด์ ์์ฑ๊ฐ ๋ํ๊ธฐ
const totalWeight=animals.reduce((acc, cur)=>{
console.log(acc, cur.weight);
return acc + cur.weight;
},0)
/*์ถ๋ ฅ๋ฌธ
0 200
200 20
220 10
230 2
*/
console.log(totalWeight); // 232
728x90
'javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ์ ์คํฌ๋ฆฝํธ ์ ๋ฌธ, ๊ธฐ๋ณธ ๋ฌธ๋ฒ (0) | 2023.09.22 |
---|---|
Array์ ํท๊ฐ๋ฆฌ๋ ๋ฉ์๋ ์ ๋ฆฌ(Array.from, arr.sort, arr.shift, arr.unshift) (0) | 2023.09.04 |
react-query ๊ฐ๋ , ๊ธฐ๋ณธ ๋ฌธ๋ฒ (0) | 2023.06.01 |
TypeScript ๊ฐ๋ (0) | 2023.03.27 |
Javascript ๊ฐ์ฒด(๋ฌธ์ ๊ฐ์ฒด๋ชจ๋ธ(DOM),๋ธ๋ผ์ฐ์ ๊ฐ์ฒด๋ชจ๋ธ(BOM) ,๋ด์ฅ๊ฐ์ฒด) (0) | 2022.01.17 |