簡體   English   中英

可以使用數組文字表示法添加非數組屬性鍵嗎?

[英]Possible to add a nonArray property key with array literal notation?

假設我有一個數組,然后向其中添加一個非數組索引 object 屬性:

 let a = [1,2,3]; a['tobey'] = 'marguire'; for (let [idx, elem] of Object.entries(a)) { console.log(idx, '==>', elem); }

有沒有一種方法可以直接使用文字表示法來執行此操作,或者是否需要僅使用點/括號設置器表示法單獨添加?我想一種方法可能是這樣,但也許它的意圖並不明確:

 let a = {...[1,2,3], tobey: 'maguire'}; for (let [idx, elem] of Object.entries(a)) { console.log(idx, '==>', elem); }

我不推薦這樣做,但一種方法如下:

 const a = [1,2,3]; Object.defineProperty(a, 'tobey', { value: 'maguire', enumerable: true }); for (let [idx, elem] of Object.entries(a)) { console.log(idx, '==>', elem); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM