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?
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);
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);
}
You can use Array.from
Array.from({length: 5}, i => i = false);
it can also be one solution
var boolArray = [true,false];
console.log(boolArray);
You may use Array.apply and map…
var numeroPerguntas = 5;
var a = Array.apply(null, new Array(numeroPerguntas)).map(function(){return false});
alert(a);
Wouldn’t it be more efficient to use an 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>
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 .