在Angular Component中,我想使用不同的变量。例如:
export class AppComponent{
value1;
value2;
value3;
value4;
print(position)
{
console.log(this.('value'+position));
//position will have values like 1,2,3,4 and I want to access value1, value2,value3,value4
//variables accordingly.
}
} 如何执行此操作?
发布于 2021-06-12 20:22:45
class AppComponent {
constructor() {
this.value1 = "val1";
this.value2 = "val2";
this.value3 = "val3";
this.value4 = "val4";
}
print(position) {
console.log(this['value' + position]);
}
}
appComponent = new AppComponent();
appComponent.print(4);
class AppComponent {
constructor() {
this.value1 = "val1";
this.value2 = "val2";
this.value3 = "val3";
this.value4 = "val4";
}
print(position) {
console.log(this['value' + position]);
}
}
appComponent = new AppComponent();
appComponent.print(4);发布于 2021-06-12 20:10:03
它是用computed property names实现的
export class AppComponent{
value1;
value2;
value3;
value4;
print(position)
{
console.log(this['value' + position]);
// or with template literals
// console.log(this[`value${position}`]);
}
}发布于 2021-06-12 20:16:16
将引用从点表示法更改为方括号表示法,您将实现您所希望的结果。
export class AppComponent {
value1 = 1;
value2 = 2;
value3 = 3;
value4 = 4;
constructor() {
this.print(3); // will print 3
}
print(position: number): void {
console.log(this[`value${position}`]);
}
}https://stackoverflow.com/questions/67948706
复制相似问题