我正在尝试构建“愿望 list ”功能。当您单击按钮时,它会将特定“属性”的名称和链接保存在本地存储的数组中。然后我会将其输出到用户的页面上。
到目前为止它有效,我唯一的问题是它总是会插入属性名称和链接,即使它已经存在于数组中。我需要创建一个检查,看看它是否已经存在,并且只有在找不到它时才推送它。
这是一个可以运行的 JSFiddle。单击“保存”按钮并检查 localStorage,您将看到数据已添加。但再次单击同一按钮,您会看到它再次被添加。
https://jsfiddle.net/g9kkx3fh/3/
这是基本代码。它从最近单击的按钮获取属性名称和链接,从 localStorage 中的数组中提取数据,然后使用 .push
添加新数据,然后重新字符串化并将其添加回 localStorage。
var name = $(this).closest('.text-long').find('.intro-text h4').text();
var permalink = $(this).closest('.text-long').find('.button-slot a').attr('href');
var property = [name, permalink]; // create an array of the name + permalink
var wishlist = JSON.parse(localStorage.getItem("wishlist")); // get the wishlist from storage
wishlist.push(property); // append the new array into the wishlist from storage
localStorage.setItem('wishlist', JSON.stringify(wishlist)); // put the wishlist back in storage
我知道我需要迭代数组,是多维的,并寻找相同的 name
变种所以我从这个开始:
for (var i = 0; i < wishlist.length; i++) {
var isPresent = ($.inArray(name, wishlist[i]));
}
if (isPresent == -1){
wishlist.push(property);
localStorage.setItem('wishlist', JSON.stringify(property));
}
这就是问题所在。如果 localStorage var wishlist
为空,则其length
是 0。因此 for
循环永远不会工作,因为 i < wishlist.length
从来都不是真的,因为wishlist
始终为 0。
那么我该如何解决这个问题呢?我永远无法向数组添加任何内容,因为我永远无法获取 isPresent
的值,因为我的for
循环永远不会工作。
这是一个用于损坏代码的 JSFiddle,但添加了 for 循环和 if 语句:
https://jsfiddle.net/bdxa0sgz/1/
我还尝试了以下方法:
if (isPresent == -1 || wishlist.length == 0){
...
}
这样,如果愿望 list 为空,它仍然会运行。然而,这似乎把 name
混在一起了。数据并覆盖数组。我很困惑。
最佳答案
在将 property
数组推送到 wishlist
数组之前,您必须检查 wishlist
是否包含正确的内容。所以你可以简单地这样做。让我们发明一个通用的 Array.prototype.compare() 方法。然而,由于这将是一个通用方法,它还考虑了数组元素是对象的可能性。所以我们也有一个 Object.prototype.compare()
(在本例中我们不需要它,但知道它很高兴)所以这里是代码;
Object.prototype.compare = function(o){
var ok = Object.keys(this);
return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};
Array.prototype.compare = function(a){
return this.every((e,i) => typeof a[i] === "object" ? a[i].compare(e) : a[i] === e);
};
var button1 = ["29 Melton Road32 York Road","http://localhost:8888/test-properties/properties/29-melton-road/"],
button2 = ["32 York Road","http://localhost:8888/test-properties/properties/32-york-road/"],
wishlist = [],
push2wl = btn => wishlist.some(a => a.compare(btn)) ? wishlist : wishlist.concat([btn]); // if exists return wishlist untouched
wishlist = push2wl(button1);
wishlist = push2wl(button2);
wishlist = push2wl(button1); // this won't get inserted
wishlist = push2wl(button2); // this won't get inserted
console.log(wishlist);
我使用箭头函数,但如果您希望代码在 Safari 9 或 IE 上运行,您可以将它们替换为传统的对应函数。
关于javascript - 在推送到数组之前先搜索多维数组,没有重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37879512/