How to initialize a boolean array in javascript

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++)

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?

I know it’s late but i found this efficient method to initialize array with Boolean values

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

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++) {


You can use Array.from
Array.from({length: 5}, i => i = false);

it can also be one solution

var boolArray = [true,false];

You may use Array.apply and map…

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

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

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

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to remove element from an array in JavaScript?

Similar Posts