Array is null when trying to use .push after localstorage - javascript

I get a TypeError saying my array is null when I try to push a new value into it.
//first off..
var sillyArray= ["dummy"];
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
//I later used this
sillyArray = JSON.parse(localStorage.getItem("sillyArray"));
//the error is here
sillyArray.push("yes");
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
Am I unable to push or parse this?
(Edited a posting error)

The yesArray was never definded. That's why it's impossible to .push().

Yes, you can but you are trying to push an item into a undefined var, this is why you get a TypeError.
Here is how you should do that:
var array = ['dummy'];
localStorage.setItem('someKey', JSON.stringify(array));
array = JSON.parse(localStorage.getItem('someKey'));
array.push('foo');
localStorage.setItem('someKey', JSON.stringify(array));
then if you do
console.log(JSON.parse(localStorage.getItem('someKey')))
the output will be what you are expecting ["dummy", "foo"]

As user nnnnnn said, I hadn't properly executed mylocalStorage.setItem("sillyArray", JSON.stringify(sillyArray));
It was sitting in an if statement (not pictured) that wasn't executing causing the null.
Thanks guys!

Related

Commerce.js cart.line_items is not returning as an array at the start and is giving me an error

I am trying to find whether my cart is empty by using const isEmpty = !cart.line_items.length;, but it is returning Cannot read property length of undefined. So i console.logged whether cart.line_items is an array and it ends up returning false, true, true. So for some reason it isnt recognized as an array at the start. How would I fix this?
Adding this catch if(!cart.line_items) return 'Loading...' seemed to solve the problem

Saving and getting an array in Localstorage?

I am trying to save an array into localstorage and then get it.
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem(savedquestionslist));
The variable 'questions' is an array.
However I get this error:
ReferenceError: savedquestionslist is not defined.
I still get the error even if I do this:
localStorage.setItem("savedquestionslist", "test");
console.log(localStorage.getItem(savedquestionslist));
Does anyone know what the issue is? Thanks
savedquestionslist needs to be a string.
console.log(localStorage.getItem('savedquestionslist'));
The problem is in your syntax for getItem.
It takes in a string as an argument. You are passing a variable and the error represents that the variable savedquestionslist is not defined.
Change your code to :
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));
An example would be
var questions = ['firstQuestion', 'secondQuestion', 'thirdQuestion'];
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));
The error you're getting is because you forgot the quotes in the getItem call:
console.log(localStorage.getItem("savedquestionslist"));
// ------------------------------^------------------^
Or you can use literal access:
console.log(localStorage.savedquestionslist);
But in both cases, since local storage only stores strings, I'd use JSON, since otherwise your array won't be saved / retrieved correctly:
localStorage.setItem("savedquestionslist", JSON.stringify(questions));
console.log(JSON.parse(localStorage.getItem("savedquestionslist")) || []);
(The || [] is for if you've never set the item, it provides a default of an empty array.)

Setting Variable Assignments with property display

I'm still a novice when it comes to JavaScript and was trying to make my code more cleaner and was wondering why the top scenario works but the bottom doesn't? Am I missing something?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
partner.style.display = "none";
providedBy.style.display = "none";
But this does not?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
collection = partner + providedBy;
collection.style.display = "none";
In the console it gives me error saying Cannot set Property 'display' of undefined. Am I supposed to define it somewhere first? I console logged the new variable and it returned both div elements.
collection is of type string as the + operator automatically call for both their toString() function.
Now what you are trying is to access a property of collection.style which does not exist because you are operating on a string. That's the reason for the error message you are getting.
You could do something like:
var collection = [];
collection.push(document.getElementById('partner'));
collection.push(document.getElementById('providedBy'));
collection.forEach(function(element) {
element.style.display = 'none';
}
which would be something I think you are trying to archive.
just to complement the accepted answer, I think you should understand why you get this error.
For what i understand from your code, you are trying to set the css of both variables partner and providedBy to display : none.
Your first piece of code works because you do this separately, while in your second code you try to add with the (+) operator both nodes, which evaluates to the string "[object HTMLDivElement][object HTMLInputElement]".
Then you try to call .style on that string which evaluates to undefined, and then you try to call display on that undefined value, this is where you get the error.
You could leave your code just like that since there are not too many variables, but if you wanted to do something that worked on multiple variables you could
create an array
push your objects into the array
create a function that loops over the elements of the array and set their style.display = "none" to individually.
In JavaScript you have to declare all of your variables. Secondly, you can't point to two objects at once by using the + operator. JavaScript interprets this as trying to concatenate the two objects, which it can't do in this way. It will return the string [object Object][object Object]
In order to affect two Objects at the same time you would need to create a function or use an existing method.

Split not working in javascript ,Uncaught TypeError

Can someone explain me why if condition in this code isn't working?
var zaposleni=[];
for(i=1;i<brOpcija;i++){
zaposleni.push(myOpts[i].value);
}
var zaposleniRestoran=[];
for(i=1;i<brOpcija;i++){
if(zaposleni[i].split(' ').slice(2).join(' ') == vrednostSelekta()){
zaposleniRestoran.push(zaposleni[i].split(' ').slice(0,2));
}
}
Here,i have array zaposleni where i push some values,and array is look like ["name" "surname" "restaurantName"],and then i am checking if restaurantName == vrednostSelekta() (where vrednostSelekta() is return value of some function in javascript),but i always get this error:
Uncaught TypeError: Cannot read property 'split' of undefined
at HTMLSelectElement.<anonymous> (zaposleni.js:51)
at HTMLSelectElement.handle (jquery.min.js:55)
at HTMLSelectElement.o (jquery.min.js:49)
But when i erase this if,and then type that in debugger,i get no error and it is working there..Thanks in advance!
Looks like the "zaposleni" array is empty or maybe there is only one element in it. Your for loop is starting at "i=1".
In the error, Cannot read property 'split' of undefined means that you're calling .split(...) to something that isn't defined.
This means that at the beginning of the if, the script is stopping when zaposleni[i] is not defined.
This is probably because i is bigger than the length of zaposleni at the biggest value for i, as you're iterating up to the same value, but you're starting to push at i=1 rather than i=0, as array indices in JS start at 0. In other words, you're adding a value at zaposleni[0], not zaposleni[last index value], and requiring from zaposleni[1] up to zaposleni[last index value], so the last one will be undefined.
The issue may also be that myOpts[i].value is probably undefined for some values of i, so I would recommend checking that

JQuery val returning undefined

So I'm calling the following function:
function updateOutput(a){
var n = $('#selector').val();
$('#hueslide').val(a[n].hue);
$('#huetext').val(a[n].hue);
}
And I'm getting an error: "Cannot read property 'hue' of undefined."
However, when I use console.log(n), it's returning a value. And when I manually insert the same value in a[n], I get the expected result. I'm guessing this is an asynchronous issue, but the same code was working in an earlier version and I'm not sure how to fix it.
Specifically, when trying to debug updateOutput using console.log, I get the following:
console.log(n); //returns 0
console.log(a); //returns an array of objects
console.log(a[0]); //returns first object in array
console.log(a(n)); // returns undefined
That error isn't saying that n is undefined, or even a, it's saying that there is no property hue on whatever is assigned to a[n]. Whatever you are passing into updateOutput has no key to match n that also has the property hue.
Try like this:
function updateOutput(a){
$(document).ready(function(e) {
var n = $('#selector').val();
$('#hueslide').val(a[n].hue);
$('#huetext').val(a[n].hue);
});
}
You have to wait until the element are fully loaded. That's why you have to use ready method.
Okay, I figured it out. Turns out the value of 0 in n I was passing a string. So adding n = parseInt(n); resolved the issue.

Categories