๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

javascript

Javascript ๋ฐ˜๋ณต๋ฌธ (forEach, map, filter, reduce)

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