Javascript 如何在javascript中初始化一个布尔数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27040430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a boolean array in javascript
提问by Alberto Crespo
I am learning javascript and I want to initialize a boolean array in javascript.
我正在学习 javascript,我想在 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 thisway:
谷歌搜索后,我只找到了这种方式:
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?
但是我发现这是一个非常困难的方法来初始化一个数组。有人知道另一种方法吗?
采纳答案by Andy
You were getting an error with that code that debugging would have caught. intisn't a JS keyword. Use varand your code works perfectly.
您收到调试会捕获的代码错误。int不是 JS 关键字。使用var并且您的代码完美运行。
var anyBoxesChecked = [];
var numeroPerguntas = 5;
for (var i = 0; i < numeroPerguntas; i++) {
anyBoxesChecked.push(false);
}
回答by warl0ck
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);
回答by Zahra Nawa
it can also be one solution
它也可以是一种解决方案
var boolArray = [true,false];
console.log(boolArray);
回答by Sampath Liyanage
You may use Array.apply and map...
您可以使用 Array.apply 和 map...
var numeroPerguntas = 5;
var a = Array.apply(null, new Array(numeroPerguntas)).map(function(){return false});
alert(a);
回答by Pepijn Ekelmans
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>

