如何检查ID是否存在于localStorage对象键数组中
我现在正在使用这个,但它不起作用。
if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }另外,如何将独立的对象数组分离为ID、图像、标题,以使变量
谢谢
下面是完整的代码
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
}发布于 2022-11-08 20:37:55
在提出建议后,我找到了解决办法。
我的解决方案是使用favoritesi.ID ==种族隔离在for循环中检查。
最后的代码如下。我很肯定可以用另一种方式来做,但这目前是可行的。
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');
}
}https://stackoverflow.com/questions/74365788
复制相似问题