how to set localstorage variable into a function - javascript

I have this function
function sumFood (tot,tab_cout){
var tot = 0;
for (var i=0; i<tab_cout.length;i++) {
tot += Number(tab_cout[i]);
}
localStorage.setItem('tot',tot);
}
sumFood (GLC,GLCT);
sumFood (LIP,LIPT);
I would like that GLC, LIP go into localStorage (in place of tot) but for some reasons the result I get is undefined... what to do? (console.log gives me good result of tot)

The reason you got undefined is you have hardcoded the key this line:
localStorage.setItem('tot',tot);
where it should be dynamically changed upon the parameters. Another thing you should be aware of is, it's not a good practice to name a variable inside a function the same as its parameter which is confusing. Try this:
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 save the sum in seperate keys in localStorage. In your case, I'm assuming that you want to store all the key and value pairs in only one key, which is tot in the localStorage, then the tot has to be an array of objects. Try this below:
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)
Then retrieve it later:
const getTot = JSON.parse(localStorage.getItem('tot')) || []
console.log(getTot) // you will see your expected output

I had to put return total to get what I needed, and I don't need to store. So I guess your solution is correct for the entitled
function sumFood (tot,tab_cout){
var total = 0;
for (var i=0; i<tab_cout.length;i++) {
total += Number(tab_cout[i]);
}
return total;
}
sumFood (GLC,GLCT);
sumFood (LIP,LIPT);

Related

How could I add variables according to the length of the array?

I have an array that the values ​​range from A to Z, which I want to convert to variables that depend on the input data, for example:
enter the data
362,232,113 and this becomes an array of a length of 3 unit.
so I want to assign the name of a variable depending on the length of the input array but when executing the code, it assigns the array index well, but that same index executes the length of the input array and does not assign the variables as I would like it to.
in fact when executing this happens:
(3) 326
showing that the matrix was correctly divided but the same index was executed 3 times, in summary what I want is to be executed as follows:
"A = 326" "B = 232" "C = 113"
In advance I thank you for your help
var asignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
matrix =[326,232,113];
function divide(){
xyz = matrix.split(",");
console.log(matrix);
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
console.log(A); //(2) 326
}
}
You have a typo assignLetter instead of asignLetter ( two s ) and you need to pass a string to your function for it to work :
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
}
}
console.log({A,B,C});
You should avoid creating global variabels like that, have them in an object instead
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
var myVars = {};
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
myVars[assignLetter[i]] = xyz[i];
}
}
console.log(myVars);
I think you want to pass the parameters 326,232,113 as a whole string. You're passing them as parameters wrong.
So just do the same thing you're doing but like this: divide("326,232,113")

How to print localStorage array in html for loop?

I have an array in my localStorage which contains ["January","Febuary"]
I want it to be displayed in HTML preferably like this:
Month
January
Febuary
So I've tried this code:
function show(){
for(let i = 0;i < localStorage.length;i++){
var date = JSON.parse(localStorage.getItem("date"));
}
for(var b = 0; b < nameLength; b++){
document.getElementById('storageOut').innerHTML = date[b];
console.log(date[b]);
}
}
My code above does work however, the line "document.getElementById('storageOut').innerHTML = date[b];"only prints out the last data in the array, but when i check the console it prints out both.
You create the variable date in the first for-loop and assign it to one value each iteration. Easiest way would probably be to do it in a single for-loop instead:
function show(){
for(let i = 0;i < localStorage.length;i++){
var date = JSON.parse(localStorage.getItem("date"));
document.getElementById('storageOut').innerHTML = date;
}
}
Although, if you want all the dates, you should probably append it to the innerHtml:
...innerHTML += date;
Or rather:
...innerText += date;
Assuming your contents are stored in local storage key named data. Try the following.
const data = JSON.parse(localStorage.getItem('data'))
data.forEach(item => {
document.getElementById('storageOut').innerHTML += item
})

Saving all variables using loop and localStorage [JavaScript]

I wanted to make a code that will easily save all variables. Normally i would need for 60 variables about 120 lines. Not very efficient. I decided to try to make one function with array to try to save all variables. It doesnt seem to work.
My problem is that loaded variables are string, but i need them to be float.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage[variablelist[i]] = window[variablelist[i]];
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage[variablelist[i]];
}
}
I have tried
window[variablelist[i]] = localStorage[parseFloat(variablelist[i])];
Nothing has worked. It is still a string. Any ideas ?
First of all, it hurts me to see so much stuff stored on the window object like that. You should really give that a re-think!
LocalStorage is a way of storing a key-value pair to the browsers memory for access later. The only catch is that the value has to be a string.
You can get around this my using the JSON.stringify and JSON.parse function:
var objectToSave = {
key1: 'something',
key2: 'something else'
};
localStorage.setItem('myObject', JSON.stringify(objectToSave));
console.log(localStorage.getItem('myObject')); // What is stored
console.log(JSON.parse(localStorage.getItem('myObject'))); // The parsed object
Otherwise, if you are set on saving all of the individual variables, you are not far off, you just need to use the getItem and setItem:
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], window[variablelist[i]]);
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage.getItem(variablelist[i]);
}
}
Use localStore.setItem() and localStore.getItem() to store and load items. Also use JSON.stringify() and JSON.parse() to convert objects to text, and then restore them back to objects.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], JSON.stringify(window[variablelist[i]]));
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = JSON.parse(localStorage.getItem(variablelist[i]));
}
}

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

A good way to associate a counter to each member of an array in Javascript?

I have an array of strings in Javascript like `var elements = ["string1", "string2"]; The array is created dynamically so it could contain any number of strings. I want to associate a counter to each element of the array. The counter will increment or decrement during the webpage's life.
I was going to try element["string1"].counter = 1; but it didn't work.
What's a good way to implement this?
If you had an array var elements = ["string1", "string2"], you could not access an element with elements["string1"], you are using the value not the index. elements[0] is the correct form of access to the element, using the numerical key.
Even then, strings are special types of object and do not appear to take additional parameters readily, at least not when I tested a moment ago. Which is odd.
You could quickly knock the array in to a set of objects with separate text and counter components.
var elements = ["string1", "string2"];
var elementsWithCounter = [];
for(var index = 0; index < elements.length; index++) {
elementsWithCounter[i] = { text: elements[index], counter: 1 };
}
You could also create a "hash table" using a plain object such as:
var counter = {};
for(var i = elements.length; i--; ) {
counter[elements[i]] = 1;
}
Then you could increment the counter with:
counter['string1'] += 1;
or
counter[elements[0]] += 1;
This might help you.
elementArray = ["string1", "string2"]
function setCounter(str, val) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) elementArray[i].counter = val;
}
}
function getCounter(str) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) return elementArray[i].counter;
}
}
setCounter("string1", 5);
getCounter("string1");
Alternatively just access elementArray[index].counter
Javascript primitives/built in objects can't have properties/attributes added to their prototype (i.e. String.prototype.counter = -1 doesn't work correctly). Image, String, Date, Array all can't have properties added.
Maybe instead of a string you should make it an object, similar to what Orbling has posted.

Categories