쿠키에 마지막으로 본 10 개의 제품을 저장하고 싶습니다. 고유 한 값만 유지해야합니다. 동일한 제품을 두 번 이상 저장하지 않으므로 js-cookie library을 사용하고 이것이 내 코드배열의 값이 jquery인지 확인하십시오.
function getLastViewedProducts() {
var pathArray = window.location.pathname.split('/');
var secondLevelLocation = pathArray[1];
var thirdLevelLocation = pathArray[2];
if (secondLevelLocation == 'catalog' && typeof thirdLevelLocation != 'undefined' && $("article[id^='node']").length > 0) {
var currentUrl = window.location.href;
var currentTitle = $('.node-header h1').html();
var currentImgUrl = $('.field-items .field-item:first-child a img').attr('src');
var productsArray = [{ 'url' : currentUrl, 'title' : currentTitle, 'img' : currentImgUrl }];
if (typeof Cookies.get('lastViewedProductsList') == 'undefined') {
// no cookie
Cookies.set('lastViewedProductsList', productsArray, { expires: 7 });
} else {
// have cookie
var arr = Cookies.getJSON('lastViewedProductsList');
if (jQuery.inArray(productsArray, arr)) {
if(arr.length > 10) {
arr.shift();
}
}
arr.push(productsArray);
Cookies.set('lastViewedProductsList', arr, { expires: 7 });
}
}
}
getLastViewedProducts();
그러나 내 검사 if (jQuery.inArray(productsArray, arr))
은 여기서 작동하지 않으며 배열에 동일한 값이 추가됩니다. 왜?
'productsArray' 및'arr'에 무엇이 들어 있는지 확인 했습니까? 검사를 수행하기 바로 전에'console.log (productsArray, arr)'을 실행하고 자바 스크립트 콘솔을 검사하여 데이터가 어떻게 보이는지 확인하십시오. –