[React]Error foreach/map...

Yunju·2024년 10월 31일
0

//foreach랑 map의 차이점
//reduce가 뭔지

React 모듈 첫날 과제를 받았다..

Create a table component in React, use the JSON data do the followings:
1. Display the products data in the table.
2. Calculate the total for each product.
3. Calculate the total for the entire products and display in an h1 tag

어찌어찌 테이블 1,2번까진 했지만, total for the entire products는 하지못함..

첫시도

foreach로 돌리려 함..

 tableObj.foreach((obj) => {
    totalSums += obj.amount * objprice;
  });

-->이거 안돌아감!! 지꾸 에러나..

그래서 Joy언니한테 물어본 결과

 tableObj.map((val) => (
     totalSums += val.price * val.amount
   ))

맵을 써야됨..
아님 foreach말고 for문을 돌리거나..

그래서 이것들의 차이점이 뭔지 궁금해서 찾아봄

for

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]); // 1, 2, 3, 4, 5
}

foreach

const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
    console.log(number); // 1, 2, 3, 4, 5
});

map

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((number) => number * number);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

0개의 댓글