5 글 보임 - 1 에서 5 까지 (총 5 중에서)
-
글쓴이글
-
2023년 7월 21일 17:22 #91843
병아리짹짹참가자1. 같은 상품은 중복으로 추가되지 않게하려고 같은 것이 있는지 확인하려고 합니다 첫 코드는 이랬는데
$(".buy").click(function(e){ var title = $(e.target).siblings("h5").text();
if(localStorage.getItem("cart") != null) { var ttemp =JSON.parse(localStorage.cart) ttemp.push(title) localStorage.setItem("cart",JSON.stringify(ttemp)) } else{ localStorage.setItem("cart",JSON.stringify([title])) } }) 여기서 중간에 ttemp.forEach(function(a,i){ if(ttemp[i] == title) {return} }) 을 넣어서 만약 같은 것이 있으면 return으로 함수를 중단시키려 했습니다 그래서 최종 코드는 아래와같이 짰는데 $(".buy").click(function(e){ var title = $(e.target).siblings("h5").text(); if(localStorage.getItem("cart") != null) { var ttemp =JSON.parse(localStorage.cart) ttemp.forEach(function(a,i){ if(ttemp[i] == title) {return} }) ttemp.push(title) localStorage.setItem("cart",JSON.stringify(ttemp)) } else{ localStorage.setItem("cart",JSON.stringify([title])) } }) 로 바꿨는데 별 변화가 없습니다. 놓친 부분은 무엇일까요?
2023년 7월 21일 19:35 #91857
codingapple키 마스터forEach 중간에 정지는 안될걸요 .find 아니면 .findIndex쓰면 array에 특정데이터 있는지 찾아줍니다
2023년 7월 21일 22:30 #91880
병아리짹짹참가자.findindex랑 .find 찾아보면서 짜보는데 함수 설정이 영 애매해서 어떻게 적용해야할지 모르겠어요 var chk = arr.findIndex(function (dd) { return dd[0] == arr[0]; }); console.log(chk); 여기서 arr은 장바구니 배열입니다 일단 findindex 함수를 써본적이 없는지라 확인겸 해봤는데 chk 값은 계속 -1 나오고 .find나 .findindex나 찾아서 있으면 값을 인출한다는 것 같은데 여기서 장바구니에서의 특정 값을 어떻게 해야하는지 감이 안 잡힙니다
2023년 7월 21일 23:12 #91882
병아리짹짹참가자지금은 이런 상태입니다
$(".buy").click(function (e) { var title = $(e.target).siblings("h5").text(); if (localStorage.getItem("cart") != null) { var ttemp = JSON.parse(localStorage.cart); var chk1 = ttemp.findIndex(function (kk) { kk == title; }); if (chk1 < 0) { ttemp.push(title); localStorage.setItem("cart", JSON.stringify(ttemp)); } else { return; } } else { localStorage.setItem("cart", JSON.stringify([title])); } });
제 코드의 의도는 클릭했을 때 localStorage가 없으면 밑에서 그냥 추가하고 있으면 일단 그 배열을 꺼내와서 ttemp에 저장합니다 그리고 ttemp에 현재 클릭한 title에 대해서 있는지 확인하고 있으면 그 인덱스값을, 없으면 -1을 chk1에 저장합니다 그래서 만약 chk1가 0보다 작으면(-1이면) ttemp에 현재 클릭한 상품이 없다는 뜻이므로 추가하고 chk1이 0보다 크면(index값을 가지면) return으로 함수를 빠져나옵니다 그런데 findindex쓴 chk1쪽이 작동하지 않아 고민중입니다
-
글쓴이글
5 글 보임 - 1 에서 5 까지 (총 5 중에서)
- 답변은 로그인 후 가능합니다.