코딩애플 선섕님 질문 올립니다
같은 상품 구매 누르면 상품 개수가 올라가게 하는 거 하고 하단에 다음 강의 버튼 눌렀는데
딱히 답지는 없는 것 같더라고요 제가 코딩한 방법이 괜찮은 방법인지 확신이 좀 안 들어서 다음으로 못 넘어가겠어요
코딩애플 선생님의 이상적인 답안이 너무 궁금하여 질문 올립니다..
일단 제 코드는 이렇습니다.. 2가지 방법으로 시도해봤습니다. 진짜 오늘 하루죙일 이것만 했습니다..
try1은 엄청난 실패 끝에 겨우겨우겨우 했고
try2는 코딩애플 선생님의 모르겠으면구글검색하셈이 떠올라 겨우겨우겨우 findindex찾아서 써먹었읍니다.
products.forEach(function (data, i) {
$('.buy')
.eq(i)
.on('click', function (e) {
let itemObj = {
title: $(e.target).siblings('h2').text(),
num: 1,
};
if (localStorage['length'] == 0) {
console.log('비었음');
localStorage.setItem('cart', JSON.stringify([itemObj]));
} else {
console.log('안비었음');
let getCart = JSON.parse(localStorage.getItem('cart'));
//===여기까지 잘 작동 됨===//
//---try1---//
let index = 0;
let same;
getCart.forEach((data, i) => {
if (data['title'] === itemObj['title']) {
index = i;
same = true;
}
});
if (same) {
getCart[index]['num']++;
} else if (!same) {
getCart.push(itemObj);
}
localStorage.setItem('cart', JSON.stringify(getCart));
//---try2---//
// let index = getCart.findIndex((a) => {
// return a['title'] === itemObj['title'];
// });
// if (index == -1) {
// console.log('같은거없음');
// getCart.push(itemObj);
// } else {
// console.log('같은거있음');
// getCart[index]['num']++;
// }
// localStorage.setItem('cart', JSON.stringify(getCart));
}
});
});
피드백이나 이상적인 답안 부탁드립니다..
응용문제로 혼자 이것저것 해보는데 시간은 오래 걸려도 많은 도움이 되고 있습니다 선생님 감사합니다