首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >localStorage数组对象-如何检查是否存在对象键值

localStorage数组对象-如何检查是否存在对象键值
EN

Stack Overflow用户
提问于 2022-11-08 18:50:43
回答 1查看 20关注 0票数 0

如何检查ID是否存在于localStorage对象键数组中

我现在正在使用这个,但它不起作用。

代码语言:javascript
复制
if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }

另外,如何将独立的对象数组分离为ID、图像、标题,以使变量

谢谢

下面是完整的代码

代码语言:javascript
复制
function checkfave (theid) {

// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage'+theid).attr('src');
var thetitle = $('#thetitle'+theid).text();

if (localStorage.getItem('favorites') != null) {
    if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }
}
            
    favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
    localStorage.setItem('favorites', JSON.stringify(favorites));

    alert('You Just Added Listing '+theid+' To Your Favorites');


    //Loop through the Favorites List and display in console (HIDDEN)
    console.clear();

        for (let i = 0; i < favorites.length; i++) { 
            console.log('ID= '+favorites[i].ID+'  IMAGE='+favorites[i].IMAGE+'  TITLE='+favorites[i].TITLE);
        }//for loop
                                                
}
EN

回答 1

Stack Overflow用户

发布于 2022-11-08 20:37:55

在提出建议后,我找到了解决办法。

我的解决方案是使用favoritesi.ID ==种族隔离在for循环中检查。

最后的代码如下。我很肯定可以用另一种方式来做,但这目前是可行的。

代码语言:javascript
复制
function checkfave (theid) {

var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage'+theid).attr('src');
var thetitle = $('#thetitle'+theid).text();
var added=true;

    //Loop through the Favorites List and display in console (HIDDEN)  
    for (let i = 0; i < favorites.length; i++) { 
            
    if ( favorites[i].ID == theid ) { alert('You allready Added Listing '+theid+' To Your Favorites'); var added=false; break; } else {var added=true;}
    
    }//for loop
        
                
        if (added===true) {
            favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
            localStorage.setItem('favorites', JSON.stringify(favorites));
            alert('You Just Added Listing '+theid+' To Your Favorites');
        }


                                                
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74365788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档