我想在Cookie中保存最近10个已浏览的产品,我只需要保留唯一值,我的意思是,不要将同一产品保存两次或更多次,所以我使用js-cookie library这是我的代码< / p>
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))
在这里工作并且在数组中会添加相同的值。为什么呢?
答案 0 :(得分:1)
jQuery.inArray()检查单个值是否在数组中。在提供的代码中,products数组是一个单独的元素,您永远不会向它添加任何内容。在设置cookie时,最好只声明单个对象并将其包装在数组中。
var product = {'url':currentUrl,'title':currentTitle,'img':currentImgUrl};
...
Cookies.set('lastViewedProductsList', [product],{expires:7});
然后,您可以查看给定的product
是否在您的lastViewedProductsList
中。您还需要比较每个对象中的单个属性,因为JavaScript中的对象比较真实性有点不稳定。为此,我们可以使用Array.reduce
var lastViewedProductsList = Cookies.getJSON('lastViewedProductsList');
var productInLastViewed = lastViewedProductsList.
reduce(function(found,lastViewedProduct){
return found || (product.url === lastViewedProduct.url);
},false);
if(productInLastViewed){
....