亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號