我有一个输入,它使用 API 根据插入的字母来获取一些城市。API 在每个keyup事件上启动,如下所示:
let ville_input = document.getElementById("search_immobilier_ville");
let ville_arr = [];
ville_input.addEventListener("keyup", () => {
res_list.innerHTML = "";
fetch("https://api.fr/communes?nom=" + ville_input.value)
.then(res => {
return res.json();
})
.then(data => {
data.forEach(el => {
if (
el.codeDepartement == "971" &&
el.nom
.toUpperCase()
.startsWith(ville_input.value.toUpperCase().trim())
) {
if (!ville_arr.includes([el.nom, el.codesPostaux[0]])) {
ville_arr.push([el.nom, el.codesPostaux[0]]);
console.log(ville_arr);
}
}
});
})
.catch(err => {
// Doing stuff
});
});
首先,我想将每个结果作为数组推送到一个数组中,如下所示:
ville_arr.push([el.nom,el.codesPostaux[0]])
我的问题是,当 API 获取相同的结果时,我将重复的项目放入我的数组中,这就是我尝试这个的原因:
if(!ville_arr.includes([el.nom,el.codesPostaux[0]])){
ville_arr.push([el.nom,el.codesPostaux[0]])
console.log(ville_arr)
}
但是我最后还是得到了重复的项目,我想这与数组的索引有关吗?也许别的什么?
