在TypeScript中如何访问数组的成员?

时间:2015-04-30 07:37:49

标签: 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"

2 个答案:

答案 0 :(得分:1)

确实有效:

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

答案 1 :(得分:0)

如果你有一个包装器(你在问题中称它为TreesArray),你需要确保包装器定义一个索引器。

interface TreesArray {
    [index: number]: tree;
}

这是一个完整的例子:

class tree{
    constructor(public treeName: string){       
    }
}

interface TreesArray {
    [index: number]: tree;
}

var treeArray: TreesArray;

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

alert(treeArray[1].treeName);