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?
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.
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!
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,...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With