The listCount-- inside the function removeItem do not pass the value in list.itemCount but the itemLists.splice(indexOfLi, 1); in the same function is perfectly removing the value in the list.itemList. I am confused, what's the problem of this? Thanks.
const list = {
itemCount: 0,
itemList: []
};
function displayValue(countText, itemLists, listCount, ulVar) {
countText.append(` (${listCount})`);
for (let i = 0; i < listCount; i ) {
createElement(itemLists[i]?.item, itemLists[i]?.time, ulVar);
}
removeItem(itemLists, listCount, countText);
}
function removeItem(itemLists, listCount, countText) {
const fontASTrash = $('.fa-trash');
fontASTrash.off().on('click', function () {
const indexOfLi = $(this).parent().parent().index();
$(this).parent().parent().remove();
itemLists.splice(indexOfLi, 1);
listCount--;
countText.text(`Item List (${listCount})`);
});
}
displayValue(itemListText, list.itemList, list.itemCount, ulItemList);
CodePudding user response:
listCount
variable inside the removeItem
function does not contain a reference to the list.itemCount
value and is actually a standalone variable.
The reason why this happens is because when the following is called:
displayValue(itemListText, list.itemList, list.itemCount, ulItemList);
The .itemCount
value is passed in as standalone primitive values that are no longer part of the list
object, so you can change it inside displayValue
and removeItem
functions but it will no longer augment the value inside the list
object.
This behaviour can also be illustrated when destructuring objects as doing the following will no longer edit the value inside list
:
const { itemCount } = list;
itemCount--; // this will no longer change list.itemCount
The fix would be to simply pass the object to the displayValue
and removeItem
functions. E.g:
displayValue(itemListText, list, ulItemList);
And use them with the object reference. e.g. list.itemCount--
.