最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - sessionStorage if value already exist - Stack Overflow

programmeradmin2浏览0评论

Found pretty good script for showing recently viewed products using sessionStorage. There is only one problem: each product could be stored and showed multiple times.

Here is jsfiddle /

There should be one more IF to check if current product is already in storage, something like this:

// check if product already in storage
if(!productExistsInStorage()) {

    var currentCount = parseInt(sessionStorage.getItem("storedCount"));

    // add to storage
    sessionStorage.setItem(currentCount.toString(), JSON.stringify(productInfo()));

    // update storedCount var by one
    sessionStorage.setItem("storedCount", (currentCount + 1).toString());

}

I tried to make it, but without any success.

Any tips how not to save product data if it was already set in sessionStorage?

Found pretty good script for showing recently viewed products using sessionStorage. There is only one problem: each product could be stored and showed multiple times.

Here is jsfiddle http://jsfiddle/r77oozh8/

There should be one more IF to check if current product is already in storage, something like this:

// check if product already in storage
if(!productExistsInStorage()) {

    var currentCount = parseInt(sessionStorage.getItem("storedCount"));

    // add to storage
    sessionStorage.setItem(currentCount.toString(), JSON.stringify(productInfo()));

    // update storedCount var by one
    sessionStorage.setItem("storedCount", (currentCount + 1).toString());

}

I tried to make it, but without any success.

Any tips how not to save product data if it was already set in sessionStorage?

Share Improve this question edited Dec 15, 2015 at 19:10 Toon asked Dec 15, 2015 at 15:43 ToonToon 6521 gold badge11 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Just came across this post after I've looked it up myself.

if ("value" in sessionStorage) {
    alert("yes");
}
else {
    alert("no");
}

Instead of setting separate items in sessionStorage for each product, i would set them all in one array. That would make it easier to check if it already exists:

var currentItems = JSON.parse(sessionStorage.getItem('products'));
var currentProduct = productInfo();
if (currentItems.filter(function(p){return p.productURL == currentProduct.productURL}).length == 0) {
// add
}

Why not check is session storage for that item is null or not?

if(sessionStorage.getItem("storedCount") === null)
{
//do something
}

Even better make a function that you can pass the name of an item to to check it.

function doesStorageExist(item)
{

if(sessionStorage.getItem(""+item) === null)
{
//do something
}

}
发布评论

评论列表(0)

  1. 暂无评论