Alberto Crespo
Alberto Crespo

Reputation: 2519

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?

Upvotes: 32

Views: 87361

Answers (7)

DA_123
DA_123

Reputation: 385

    Array.from({length: 5}, () => false)

Sample:

const arr = Array.from({length: 5}, () => false)
console.log(arr.join(", "))

Upvotes: 0

agriboz
agriboz

Reputation: 4854

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

Upvotes: 4

Zahra Nawa
Zahra Nawa

Reputation: 29

it can also be one solution

var boolArray = [true,false];
console.log(boolArray);

Upvotes: 2

Pepijn Ekelmans
Pepijn Ekelmans

Reputation: 55

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>

Upvotes: 0

warl0ck
warl0ck

Reputation: 3464

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

Upvotes: 102

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

You may use Array.apply and map...

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

Upvotes: 0

Andy
Andy

Reputation: 63587

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);
}

DEMO

Upvotes: 14

Related Questions