You received an undefined value because the key
was hardcoded in this line:
localStorage.setItem('tot',tot);
The key should change dynamically based on the parameters passed. Additionally, it is not recommended to name a variable inside a function the same as its parameter as it can lead to confusion. Consider using the following approach:
function sumFood (tot,tab_cout){
var total = 0;
for (var i=0; i<tab_cout.length;i++) {total += Number(tab_cout[i]);}
localStorage.setItem(`${tot}`,total);
}
sumFood(GLC,GLCT);
sumFood(LIP,LIPT);
This will store the sums in separate keys in localStorage. If you want to store all key-value pairs under one key, such as 'tot' in localStorage, then 'tot' needs to be an array of objects. Try the following modification:
function sumFood (tot,tab_cout){
let total = 0;
for (let i=0; i<tab_cout.length;i++) {
total += Number(tab_cout[i])
}
const savedTot = JSON.parse(localStorage.getItem('tot')) || []
const addedTot = savedTot.push({ [`${tot}`]: total })
localStorage.setItem('tot', JSON.stringify(addedTot))
}
sumFood(GLC,GLCT)
sumFood(LIP,LIPT)
// if GLC
and LIP
are variables, otherwise you should put them in string. Like this:
sumFood('GLC',GLCT)
sumFood('LIP',LIPT)
To retrieve the values later on, use the following:
const getTot = JSON.parse(localStorage.getItem('tot')) || []
console.log(getTot) // you will see your expected output