arrays - 在 TypeScript 中,我如何访问数组的成员?

标签 arrays typescript

如果我有类似的东西:

var treeArray: TreesArray;
treeArray = [new tree("Maple"),
    new tree("Pine"),
    new tree("Spruce")];`

我如何提醒第二位成员?

这不起作用:alert(treeArray[1]);

更新:抱歉,我应该从一开始就包含完整的代码。正如我所写的那样,警报仍然不起作用。

interface ITrees{
    treeName: string;
}

interface TreesArray{
    [index: number]: ITrees;
    length: number;
}

class tree implements ITrees{
    treeName: string;
    constructor (treeName: string){
        this.treeName = treeName; 
    }
}

var treeArray: TreesArray;
treeArray = [new tree("Maple"),
            new tree("Pine"), 
            new tree("Spruce")];

alert(treeArray([1]);//does not alert "Pine"

最佳答案

它确实有效:

class tree{
    constructor(public treename){       
    }
    toString(){return this.treename}
}
var treeArray: tree[];
treeArray = [new tree("Maple"),
        new tree("Pine"),
        new tree("Spruce")];

alert(treeArray[1]);

Try it online by pressing run

您将获得:

enter image description here

关于arrays - 在 TypeScript 中,我如何访问数组的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29961776/

相关文章:

javascript - IE11 中的 TypeScript Array.from

javascript - 带有 Promise 的 ngOnInit 上的 ExpressionChangedAfterItHasBeenCheckedError

java - 为什么我的程序不输出数字

Python:简单 OLS super 词典

java - 某个范围内的 IP 地址

typescript :如何为 npm 模块使用本地类型声明文件

angular - 一次只选择一个复选框并在选中的特定复选框或未选中的两个复选框上执行特定任务

c - 使用 3D 数组 - 无法进行输出

python - 使用 itertools 创建 numpy 数组

arrays - 将数组传递给异步库 eachSeries - 期望 'Dictionary<{}>'