How to initialize a boolean array in javascript

Tags: , ,



I am learning javascript and I want to initialize a boolean array in javascript.

I tried doing this:

 var anyBoxesChecked = [];
 var numeroPerguntas = 5;     
 for(int i=0;i<numeroPerguntas;i++)
 {
    anyBoxesChecked.push(false);
 }

But it doesn’t work.

After googling I only found this way:

 public var terroristShooting : boolean[] = BooleanArrayTrue(10);
 function BooleanArrayTrue (size : int) : boolean[] {
     var boolArray = new boolean[size];
     for (var b in boolArray) b = true;
     return boolArray;
 }

But I find this a very difficult way just to initialize an array. Any one knows another way to do that?

Answer

You were getting an error with that code that debugging would have caught. int isn’t a JS keyword. Use var and your code works perfectly.

var anyBoxesChecked = [];
var numeroPerguntas = 5;     
for (var i = 0; i < numeroPerguntas; i++) {
  anyBoxesChecked.push(false);
}

DEMO



Source: stackoverflow