Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array push not working [closed]

I am trying to push a value into an array and it is giving me this error in the developer tools.

Uncaught TypeError: Cannot read property 'push' of null

Here is the code that it seems to be sticking on, word and local word were defined earlier like this.

var word = [];
var localWord = []; 

function setLocalArray() {
    // first get words from text field and update word array.
    word = document.getElementById("words").value.split(',');

    // store word array in localStorage            
    for(var i=0; word.length > i; i++) {
        var key2 = "part"+i;
        localStorage.setItem(key2,word[i]);
        localWord.push(key2);
    }

    localStorage.setItem("localWord",JSON.stringify(localWord));
    text2Array();
    reveal();
}

localWord.push(key2); Seems to be what it is getting stuck on. I have looked at everything I can find on the push method and I can't seem to find why it is giving me this error. Help?

Here is the full code at jsfiddle http://jsfiddle.net/runningman24/jnLtpb6y/

like image 353
urock24 Avatar asked Dec 17 '14 04:12

urock24


2 Answers

Try this...

var localWord = new Array(); //create new array
var word = new Array();

function setLocalArray() {
    word = document.getElementById("words").value.split(',');
    // store word array in localStorage             
    for(var i=0; word.length > i; i++) {
        var key2 = "part"+i;
        localStorage.setItem(key2,word[i]);
        localWord.push(key2);
    }
}
like image 160
Deenadhayalan Manoharan Avatar answered Oct 15 '22 07:10

Deenadhayalan Manoharan


I found the problem, if you look in the jsfiddle I posted I am trying to pull localWord from localStorage even though it doesn't exist and so it sets it to null. Thank you to all for the ideas and contributions.

like image 29
urock24 Avatar answered Oct 15 '22 07:10

urock24