为了账号安全,请及时绑定邮箱和手机立即绑定

javascript如何动态地将子字典附加到父字典

javascript如何动态地将子字典附加到父字典

慕工程0101907 2022-05-22 18:01:25
我有一个像这样的Javascript对象:const childDict = {  address: {    zip: "GGHG654",    city: "Morocco",    number: 40  }}我想在这样的循环中动态地将它添加到另一个父字典中:let parentDict = {}for(let i = 0 ; i < 3; i++){  parentDict["place" + i] = childDict}所以最后我得到了一个像这样的字典:{  place0: {    address: {      zip: "GGHG654",      city: "Morocco",      number: 40    }  },  place1: {    address: {      zip: "GGHG654",      city: "Morocco",      number: 40    }  }}然而,for循环给了我一个编译错误:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.  No index signature with a parameter of type 'string' was found on type '{}'.
查看完整描述

3 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

let parentDict = {}

这没有明确设置导致此问题的类型。尝试提供any如下类型:

let parentDict:any = {}

或者,更准确地说:

let parentDict:{[key: string]: object} = {}


查看完整回答
反对 回复 2022-05-22
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

您只需向父字典添加适当的接口,因为打字稿会根据初始值自动分配类型,初始值没有任何键


interface IParentDict {

    [key: string]: any; // possibly change any to the typeof child dict

}

const parentDict: IParentDict = {};


查看完整回答
反对 回复 2022-05-22
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

像这样试试


let parentDict: any = {};


另一种选择可能是以更正确的方式指定类型,例如


let parentDict: {[key: string]: any} = {};


另一种骇人听闻的方式是


let parentDict = {}


for(let i = 0 ; i < 3; i++){

    (parentDict as any)["place" + i] = childDict

}


查看完整回答
反对 回复 2022-05-22
  • 3 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号