Reputation: 155
I have 20 buttons and 20 links and descriptions inside info_array. I add click event listener to each button. On click function inside addEventListener must save unique info inside localStorage with incrementing object keys on each new button click.
Problem is that function works and saves Objects with unique value inside localStorage like 0,1,2,3,... till 10th object. When object keys reach 10 then 11th object with key 11 is not saving in localStorage, code just overwrites 10th object every time i clicked 11th,12th,13th,... button just overwrites value of 10th object rather creating and saving new object with new object key like 11,12,13,14,...
I can't understand what is wrong with my code because it works till 10th object.
Code:
for (let i = 0; i < 19; ++i) {
let btn = document.createElement('BUTTON');
btn.addEventListener('click',function(e){
e.stopPropagation();
let newsList = localStorage,
keys = Object.keys(localStorage).sort(),
match = false,
news = {
"title":info_array[i].title,
"description":info_array[i].description
};
if (nl.length > 0) {
// check if element exists in localStorage
for(let n = 0; n < newsList.length; ++n){
if (JSON.parse(newsList[keys[n]]).link == info_array[i].link) {
match = true;
}
}
// if object is unique save in localStorage
if (!match) {
let key = (parseInt(keys.pop())+1).toString();
localStorage.setItem(key,JSON.stringify(news));
}
}else{
// if localStorage is empty add first object
localStorage.setItem(0,JSON.stringify(news));
}
},{passive:true});
html.appendChild(element);
}
Upvotes: 0
Views: 247
Reputation: 114014
It's because of this line:
keys = Object.keys(localStorage).sort()
Specifically, the bug is caused by .sort()
Strings are sorted in dictionary order. So your keys are:
0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9
This logic is similar to how the words
app, big, branch, cut, dig, eye, fig, gem
are sorted. The word branch
comes afer big
and not gem
because it starts with b
. Similarly 10
comes after 1
and not 9
because it starts with the letter 1
.
When you pop the last key and add 1 to it you will get 10
because the last key is always 9
.
Upvotes: 1