【发布时间】:2021-01-17 20:39:20
【问题描述】:
正如问题所说,当我将对象推入对象数组时,它会复制该数组中已经存在的对象。只有在页面重新加载后,副本才会被删除。我知道这与参考有关。我尝试复制推送到数组中的对象,创建了一个带有道具的新对象,全部无效。任何帮助,将不胜感激。谢谢
// The persons array is an array of objects
import { persons } from './main.js';
let entriesFound = []
let data = localStorage.getItem('entriesFound') ;
if(data){
entriesFound = JSON.parse(data)
loadList(entriesFound)
}
//Renders the search results to the UI from localStorage
function loadList(array) {
for(let el of array) {
const html =
`<div id="${el.id}" class="item2">
<div class="info2">Name:<div class="name">${el.name}</div></div>
<div class="info2">Date of birth:<div class="born">${el.dob}</div></div>
<div class="info2">Age:<div class="age">${el.age}</div></div>
<div class="info2">Place of birth:<div class="city">${el.city}</div></div>
<div class="info2">ID:<div class="id">${el.id}</div></div>
<div class="info2">Entered:<div class="added">${el.entered}</div></div>
</div>`;
document.querySelector('.searchResult').insertAdjacentHTML('beforeend', html)
}
}
//Search button to search for entry (in the persons array) that matches the condtional
export const searchBtn = document.querySelector('.search').addEventListener('click' , function() {
// Get search string from search bar
const name = document.querySelector('.searchInput')
// persons array
persons.filter( el => {
if(el.name === name.value) {
entriesFound.push(el); // Pushes the object (el) to the entriesFound array
} // I guess this is were it goes wrong
})
addItem(entriesFound)
name.value = ""
localStorage.setItem('entriesFound', JSON.stringify(entriesFound))
})
// Renders the new search result to the UI
function addItem(entries) {
for( let item of entries) {
const html =
`<div id="${item.id}" class="item2">
<div class="info2">Name:<div class="name">${item.name}</div></div>
<div class="info2">Date of birth:<div class="born">${item.dob}</div></div>
<div class="info2">Age:<div class="age">${item.age}</div></div>
<div class="info2">Place of birth:<div class="city">${item.city}</div></div>
<div class="info2">ID:<div class="id">${item.id}</div></div>
<div class="info2">Entered:<div class="added">${item.entered}</div></div>
</div>`;
document.querySelector('.searchResult').insertAdjacentHTML('beforeend', html)
}
}
【问题讨论】:
-
使用
persons.forEach()代替persons.filter()。 filter() 方法创建一个新数组,其中包含所有通过测试的元素,在这种情况下不需要它。 -
是的,我知道,我确实做到了,但这并没有解决我在那个阶段的问题。无论如何感谢您的检查。
标签: javascript arrays object local-storage push