[英]Typescript throws error when declearing a variable as this.x = x
[英]typescript const x = […this.x]
我有一些繼承的打字稿代碼,看起來像這樣(在函數內部):
const Statuses = [...this.Statuses]
this.Statuses是指在同一.ts文件中定義的狀態代碼數組(定義為Statuses = status [];)。 上一行之后,代碼在“狀態”上運行
我試圖了解[... this.var]語法的作用? 為什么不首先簡單地引用this.Statuss?
是的,我是javascript / typescript的新手。
提前致謝。
它的“ 擴展符號 ”,它向外擴散this.Statuses
(必須是某種可迭代,如陣列)轉換成離散的元件。 在這種情況下,它們形成一個新數組(因為...this.Statuses
在[]
,它創建一個數組)。
因此,如果this.Statuses
是一個數組,則其功能與const Statuses = this.Statuses.slice();
相同const Statuses = this.Statuses.slice();
(或以下內容)。
如果this.Statuses
是另一種Iterable,則其功能與const Statuses = Array.from(this.Statuses);
相同const Statuses = Array.from(this.Statuses);
。
這是一種復制數組的美觀方法,可避免對原始數組的更改。 如其他答案中所述,它使用傳播語法。
const a = [ 1 ] const b = a const c = [...a] b.push(2) c.push(3) console.log(` original: ${a}`) console.log(`reference: ${b}`) console.log(` copy: ${c}`)
它是傳播語法 。 它允許將項目從一個數組(或對象)復制到另一數組(或對象)。 在你的情況下,它用來制造的淺表副本this.Statuses
避免原數組突變。 為此,例如,當您將新項目推送到Statuses
時,此功能非常感謝,原始數組( this.Statuses
)將保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.