问题描述
我在 Typescript 中声明或使用布尔数组时遇到问题,不确定哪个是错误的.我收到 undefined
错误.我应该使用 JavaScript 语法还是声明一个新的 Array 对象?
I'm having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an undefined
error. Am I supposed to use JavaScript syntax or declare a new Array object?
以下哪一种是创建数组的正确方法?
Which one of these is the correct way to create the array?
private columns = boolean[];
private columns = [];
private columns = new Array<boolean>();
如何将所有值初始化为 false?
How would I initialize all the values to be false?
我将如何访问这些值,我可以像这样访问它们吗,columns[i] = true;
..?
How would I access the values, can I access them like, columns[i] = true;
..?
推荐答案
以下是在打字稿中创建布尔数组的不同方式:
Here are the different ways in which you can create an array of booleans in typescript:
let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
您可以使用索引访问它们:
You can access them using the index:
console.log(arr[5]);
然后您使用 push 添加元素:
and you add elements using push:
arr.push(true);
创建数组时,您可以提供初始值:
When creating the array you can supply the initial values:
let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
这篇关于在 TypeScript 中声明一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!