当用户单击我的网页上的某些项目时,我想将项目详细信息存储在这样的对象数组中:
[{ "color": "blue", "shape": "square" } , { "color": "red", "shape": "triangle" }]
但是,当我尝试执行以下代码时,将引发错误push(tempObj)
:
export class MyComponent implements OnInit {
itemsClicked: {color: string, shape: string}[] = [];
ngOnInit(): any { }
onItemClick(color, shape) {
let tempObj = {};
tempObj["color"] = color;
tempObj["shape"] = shape;
this.itemsClicked.push(tempObj);
}
}
错误:
Argument of type '{}' is not assignable to parameter of type '{ color: string; shape: string; }'.
[]
不是任何类型的数组,而是一个空数组,因此您无法向其推送任何内容。给它一个实际的类型:
itemsClicked: {color: string, shape: string}[]
还要确保在构造函数中分配它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句