Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 434
Alberto Crespo Avatar asked Nov 20 '14 13:11

Alberto Crespo


People also ask

How is a boolean array initialized?

An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays. fill() method in such cases.

How do you initialize a boolean array in TypeScript?

To declare an array of booleans in TypeScript, set the type of the array to boolean[] , e.g. const arr: boolean[] = [] . If you try to add a value of any other type to the array, the type checker would show an error. Copied!

How do you initialize an array in JavaScript?

You can initialize an array with Array constructor syntax using new keyword. The Array constructor has following three forms. Syntax: var arrayName = new Array(); var arrayName = new Array(Number length); var arrayName = new Array(element1, element2, element3,...


1 Answers

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);
    console.log(anyBoxesChecked);
like image 116
warl0ck Avatar answered Oct 15 '22 21:10

warl0ck