0

I have an array with multiple variables defined in it. But when trying to set each of them to 0 I get an error that states the first variable of the array is undefined.

Here is what I have:

var keys = [key1, key2, key3, etc...];

function loadKeys(){
    for(i=0;i<36;i++) {
        keys[i] = 0;
    }
}
wahle509
  • 666
  • 3
  • 9
  • 22

3 Answers3

2

The error is being cause because key1 is undefined as a variable. There are actually several different ways you could do this, including manually setting the keys.

var keys = [0,0,0,0...]

instead of typing all this out however if your keys have a default value you could always initialize the array with a push command

var keys = [];
for (int i= 0; i<36;i++){
    keys.push({defaultValue});
}

that will make all the elements in you array defined with a default value rather than as an undefined element

theDarse
  • 749
  • 5
  • 13
2

Your code fails with a ReferenceError because key1, key2 etc don't exist - the JavaScript runtime doesn't know what value you are asking for.

Your example doesn't actually need these variables to be set. If you simply want an Array of 35 elements, all set to 0, you can use:

var keys = [];
for(var i = 0; i < 36; i ++) {
  keys.push(0);
}

For other ways to do this, see Most efficient way to create a zero filled JavaScript array?

Looking a small distance into the future, ES6 provides Array.prototype.fill:

var keys = new Array(35);
keys.fill(0);

This method is not widely implemented yet, but you can try it out in Firefox 31+.

ES6 compatibility table

Community
  • 1
  • 1
joews
  • 29,767
  • 10
  • 79
  • 91
0
var keys = ['key1', 'key2', 'key3'];

function loadKeys(){
    for(i=0;i<36;i++) {
        keys[i] = 0;
    }
}

is working for me so far. I don't get your issue though, are those variables in your array ?

Valentin Roudge
  • 555
  • 4
  • 14