1

我不明白为什么解构赋值后,itemsprop 不等于Gorilla

将在删除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"

4

3 回答 3

3

在此处初始化的解构声明中:

let { items:w = "Gorilla" } = options;

语法意味着声明一个名为“w”的变量,其值应初始化为“options”引用的对象中名为“items”的属性的值,或者如果没有这样的属性,则为字符串“Gorilla” .

那么,在您的情况下,变量“w”被初始化为原始对象中“items”属性的值。

如果您不想从源对象中获取值,请不要:

let w = "Gorilla";
于 2018-01-07T15:15:16.493 回答
2

当你分析代码时,你会得到三种技术在这里工作:

  1. 短手属性

    { foo, bar }
    

    为了

    { foo: foo, bar: bar}
    
  2. 默认值

    { foo = 42 }
    

    这是

    { foo: foo = 42 }
    
  3. Object Property Assignment Pattern [You Don't Know JS: ES6 & Beyond, Chapter 2: Syntax]中目标的改变:

    这里的句法模式是source: target(或value: variable-alias)。

    { foo: bar }
    

合成是w旧属性的新目标,items默认值为'Gorilla'.

于 2018-01-07T15:11:19.250 回答
0
let options = {
  size: 100,
  items: "Piggi"
}

let { title="Menu", items:w="Gorilla", size } = options;

let a = title;
let b = w;
console.log(a + " - " + b);

解决方案- 问题是,我们正在覆盖全局对象。这就是为什么你有标题作为菜单但选项对象没有标题属性。因此,当您使用选项分配全局对象时,它仍然具有“piggi”项,而且您不能像这样分配对象,您必须在 javascript 中重新分配每个属性。 我希望你得到你的答案。

于 2018-01-07T15:28:10.930 回答