Javascript 为变量赋值显示只读错误
组件。tsJavascript 为变量赋值显示只读错误,javascript,arrays,angular,typescript,variables,Javascript,Arrays,Angular,Typescript,Variables,组件。ts export class AppComponent { details:{a: boolean, b:boolean, c:boolean, x:number} = { a: false, b: false, c: false, x: 0, }; public get value(): number { const numbermap = { a: 1, b: 2,
export class AppComponent {
details:{a: boolean,
b:boolean,
c:boolean,
x:number} = {
a: false,
b: false,
c: false,
x: 0,
};
public get value(): number {
const numbermap = { a: 1, b: 2, c: 3 } //value of checkboxes;
return Object.entries(this.details)
// get only the entries with true value
.filter(([_key, value]) => value)
// map the keys having true to an array of numbers
.map(([key]) => numbermap[key])
// requred for preventing error from reduce if none selected `[].reduce()`
.concat(0)
// sum the numbers with reduce
.reduce((prev = 0, curr) => prev + curr)
}
submit() {
this.value = this.details.x; //Assigning value to variable
console.log(this.value);
}
}
我正在做的是我已经创建了一个Cheeckbox a,b,c,它分别持有1,2,3的值。如果为true,则会添加每个复选框值。但是当我试图将这个值赋给x(在细节数组中)时,我得到一个错误“x是一个只读属性”。您的
值getter方法的名称与实例上的值属性冲突。你可以:
- 选择其他名称,例如,使用
getValue
而不是value
getter,允许您将this.value
用作常规属性
- 还为
值添加一个setter,例如:
set value(newValue) {
this._value = newValue;
}
(并定义此的类型。_值
)
- 由于该值看起来唯一要使用的位置是在
submit
中,因此可以完全删除对实例的赋值,并使用局部变量,如果您打算这样做的话:
submit() {
const val = this.details.x;
console.log(val);
}
您需要为分配值给值的作业定义一个集合
例如:
public set value(new_value: number) {
this.details.x = new_value;
}
这是Vue文件?,是React?,VanillaJS的Typescript?你尝试了什么,你得到了哪些错误也是有价值的。不仅仅是问题本身它是角度10我想在细节对象中将值推到“x”当我这样做时,它说只读错误你是想做这个.details.x=这个.value
?您当前的代码与此相反是的,我需要将该值推送到this.x.value,以便我可以将其发送到firebase,或者它为dataWhat is new_value?您要为detalies.x实例设置的值。然后在提交
函数中使用set。