[英]Destructuring declaration bug with the value
我不明白為什么解構賦值后, items
道具不等於Gorilla
。
將在刪除主要道具items: "Piggi"
原始對象選項中的items: "Piggi"
后使用。 我不理解為什么...
'use strict'; let options = { size: 100, items: "Piggi" } let { title="Menu", items:w="Gorilla", size } = options; let a = title; let b = w; console.log(a + " - " + b); // must be "Menu - Gorilla"
在具有初始化的銷毀結構聲明中:
let { items:w = "Gorilla" } = options;
該語法意味着聲明一個名為“ w”的變量,該變量的值應初始化為“ options”所引用的對象中名為“ items”的屬性的值,或者如果沒有這樣的屬性,則應初始化為字符串“ Gorilla” 。
然后,在您的情況下,變量“ w”被初始化為原始對象中“ items”屬性的值。
如果您不想從源對象獲取值,請不要:
let w = "Gorilla";
分析代碼時,您可以在這里使用三種技術:
{ foo, bar }
對於
{ foo: foo, bar: bar}
{ foo = 42 }
這是
{ foo: foo = 42 }
在對象屬性分配模式中更改目標[您不知道JS:ES6及更高版本,第2章:語法] :
這里的語法模式是
source: target
(或value: variable-alias
)。
{ foo: bar }
綜合是舊屬性items
的新目標w
,默認值為'Gorilla'
。
let options = {
size: 100,
items: "Piggi"
}
let { title="Menu", items:w="Gorilla", size } = options;
let a = title;
let b = w;
console.log(a + " - " + b);
解決方案 -問題是,我們正在覆蓋全局對象。 這就是為什么您擁有Title作為Menu但選項對象沒有titile屬性的原因。 因此,當您為全局對象分配選項時,它仍然具有“ piggi”項,並且您無法像這樣分配對象,因此必須在javascript中重新分配每個屬性。 我希望你能得到答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.