【问题标题】:Destructure object property AND whole object itself [duplicate]解构对象属性和整个对象本身[重复]
【发布时间】:2021-03-28 23:16:18
【问题描述】:

我有一个对象。我知道我可以解构以检索任何条目的值,并使用扩展运算符来检索其余部分

const [a, ...rest] = [1, 2, 3];
console.log(a); // 1
console.log(rest); // [ 2, 3 ]

我想知道是否有任何 sintaxis 来检索任何条目的值,以及对象本身被重新声明为新的 var,类似于以下内容——尽管我知道是错误的——:

const [a], myArrayInANewVar = [1, 2, 3];
console.log(a); // 1
console.log(myArrayInANewVar); // [ 1, 2, 3 ]

提前致谢!

【问题讨论】:

    标签: javascript destructuring


    【解决方案1】:

    为什么不做两个作业?

    const myObject = {
      a: 1,
      b: 2,
    };
    
    const
        { a } = myObject,
        { ...copy } = myObject;
    
    console.log(a);
    console.log(copy);

    链式赋值不起作用,因为嵌套变量是在实际范围之外创建的。

    function ownScope() {
        const
            myObject = { a: 1, b: 2, },
            { a } = { ...copy } = myObject;
    
        console.log(a);
        console.log(copy);
    }
    
    ownScope();
    console.log(copy); // global

    【讨论】:

    • 抱歉,更新了示例:假设我们在变量中没有数组/对象,但我们想直接解构数组/对象。也更新为使用数组,虽然我希望会有类似的语法——如果它存在的话——
    【解决方案2】:
    const [a] = (myArrayInANewVar = [1, 2, 3]);
    console.log(a); // 1
    console.log(myArrayInANewVar); // [ 1, 2, 3 ]
    

    【讨论】:

    • 对,我在想我自己这个结构有一个链式分配,这种结构的缺点是在内部变量的范围之外获得一个全局变量。为了证明这一点,您可以将所有内容移入一个函数并在外部调用myArrayInANewVar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多