我有以下枚举:
export enum Probability {
Certain = 1,
AlmostCertain = 2,
Likely = 3,
Unlikely = 4,
AlmostImpossible = 5,
Impossible = 6,
}
数字在下拉列表中被引用,所以当我检索值时,我得到“1”,“2”等。
我遇到的问题是尝试将该值用作“枚举”。
例如:
export function probabilityLabel(probability: Probability): string {
switch (probability) {
case Probability.Certain:
return "Certain";
case Probability.AlmostCertain:
return "Almost Certain";
然后称之为: probabilityLabel(this.form.get('probability')。value)//所以基本上传入“1”
这不匹配。
如何从“1”到达传入时匹配的东西?
我试过的一些方法...... ProbabilityLabel( “1”);
让概率:概率=概率[“1”];
console.log(“第二次尝试”,ProbabilityLabel(概率));
我在这里创建了一个可复制的plunkr: http://plnkr.co/edit/8sGJeDGL0wmgBU9WxtQ4?p=preview
答案 0 :(得分:1)
enum Probability {
Certain = 1,
AlmostCertain = 2,
Likely = 3,
Unlikely = 4,
AlmostImpossible = 5,
Impossible = 6
}
let p:Probability;
p = Probability.Unlikely;
alert(Probability[p]);
enum Probability2 {
Certain,
AlmostCertain,
Likely,
Unlikely,
AlmostImpossible,
Impossible
}
let p2:Probability2;
p2 = Probability.Unlikely;
alert(Probability[p2]);
let s: string = Probability[p2];
alert(s);
let p3: Probability2 = Probability[Probability[s]];
alert(p3);
let p4: Probability2 = [Probability[s]];
alert(p4); // Will be number
请参阅here您可以在Typescript playground中运行此代码。
(很遗憾,代码会因某种URL限制被截断,但您可以从上方复制/粘贴并在操场上运行)
BTW你不需要枚举中所有值的数字。第一个将被抵消。因此,某些= 5,将使AlmostCertain 6,Likely 7等。
如果您执行p4:概率2 =概率[s]如果您发出警告,您将获得一个号码