How to initialize boolean array in javascript

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

I tried to do this:

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

      

But it doesn't work.

After resorting to help I only found this path:

 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 is a very tricky way to just initialize the array. Does anyone know another way to do this?

+9


source to share


4 answers


You got an error with the code that the debugger would have caught. int

is not a JS keyword. Use it var

and your code works fine.

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

      



DEMO

+7


source


I know this late, but I found this efficient method to initialize an array with boolean values



    var numeroPerguntas = 5;     
    var anyBoxesChecked = new Array(numeroPerguntas).fill(false);
    console.log(anyBoxesChecked);
      

Run codeHide result


+26


source


You can use Array.apply and map ...

var numeroPerguntas = 5;  
var a = Array.apply(null, new Array(numeroPerguntas)).map(function(){return false});
alert(a);
      

Run codeHide result


0


source


Wouldn't it be more efficient to use integer and bitwise operations?

<script>
var boolarray = 0;

function comparray(indexArr) {
  if (boolarray&(2**(indexArr))) {
    boolarray -= 2**(indexArr);
    //do stuff if true
  } else {
    boolarray += 2**(indexArr);
    //do stuff if false
  }
}
</script>

      

0


source







All Articles