将值从html表单分配给嵌套的javascript对象
我有一个属性详细信息,它是一个嵌套对象。 单击“登录”后,我会得到一个表单对象,其中包含要将表单中的值设置到嵌套对象中的值。为什么我们不能使用普通.(点)运算符或将值从html表单分配给嵌套的javascript对象,javascript,typescript,Javascript,Typescript,我有一个属性详细信息,它是一个嵌套对象。 单击“登录”后,我会得到一个表单对象,其中包含要将表单中的值设置到嵌套对象中的值。为什么我们不能使用普通.(点)运算符或[]来链接和访问嵌套对象及其属性 export class AppComponent { details:{ city:string, dates:{ date:Date, data:{ name:string,
[]
来链接和访问嵌套对象及其属性
export class AppComponent {
details:{
city:string,
dates:{
date:Date,
data:{
name:string,
comment:string
}[]
}[]
}
// this function is executed on submit of the form
onSignin(form:NgForm){
console.log(form)
this.details.city=form.value.city; // cannot set property 'city' of undifined
console.log(this.details)
}
}
我看你的结构或代码没有任何问题。您可能没有正确分配值 以下代码提供了正确的输出:
class Example {
details: {
city: string,
dates: {
date: Date,
data: {
name: string,
comment: string
}[]
}[]
} = {
city: "Tokyo",
dates: [
{
date: new Date(),
data: [
{
name: "Stackoverflow",
comment: "Hi"
}
]
}
]
}
getDetails() {
console.log(this.details.city)
this.details.city = "Hong Kong";
console.log(this.details.city)
}
}
new Example().getDetails();
首先打印“东京”,然后打印“香港”。
您刚刚将详细信息定义为变量,没有指定任何值。由于详细信息当前未定义,因此不能直接设置其嵌套对象中只有一个对象的值。如果详细信息已分配给任何非空值,则可以为城市设置值。如错误消息所示,
此。详细信息未定义。您需要先创建对象,然后才能设置其属性。例如:
// A cast is required because `this.details` doesn't yet have the required properties.
this.details = {} as any;
this.details.city = form.value.city;
// ...
或者使用对象文字而不是设置单个属性:
this.details = {city: form.value.city, dates: [ /*...*/ ]};
我觉得不一样。