Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在对象内使用分解指定_Javascript_Typescript_Ecmascript 6 - Fatal编程技术网

Javascript 如何在对象内使用分解指定

Javascript 如何在对象内使用分解指定,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,是否可以在对象内部使用分解赋值 这很有效 const test = {a: 'hey', b: 'hello'} const {a,b} = test; const destruct = { a, b }; 我想这样做 const test = {a: 'hey', b: 'hello'} // something like this const destru

是否可以在对象内部使用分解赋值

这很有效

        const test = {a: 'hey', b: 'hello'}
        const {a,b} = test;
        const destruct = {
            a,
            b
        };
我想这样做

    const test = {a: 'hey', b: 'hello'}
    // something like this
    const destruct = {
        {a,b}: test
    };

    const destruct = {
        {a}: test,
        {b}: test
    };

如果我理解正确,它似乎是一个很好的适合你需要的

扩展语法“
”允许您将键/值对从源对象(即
test
)扩展到目标对象(即
destruct
):

const测试={
a:‘嘿’,
b:你好,
c:再见
}
const destruct={

//{a,b}:test如果要获取属性的子集,可以使用rest操作符

const测试={
a:‘嘿’,
b:你好,
c:再见
};
const{c,…destruct}=test;

console.log(destruct);
您可以尝试这样对数组进行分解

    let abc = {
      a: 'hello',
      b: 'hey',
      c: 'hi, there!'
    }


    let {a: x, b:y, c:z} = abc;

    console.log(x,y,z)  

// "hello"
   "hey"
   "hi, there!"

如果你想要一个浅层的副本,
{…obj}
就可以了。如果你想要属性的子集,你必须去构造(或者只做
{a:test.a,b:test.b}
)。@lawrencerone是的,你可以,使用像
const k=“foo”;const o={[k]:“bar”};
会产生
o={foo:{bar}
我认为OP是在你的第二个版本之后,这是一个非常简洁/酷的btwUpon测试,为什么
…({a,b}=test)
的工作原理是一样的,第二部分是干什么的?@Lawrencerone感谢你的反馈-我刚刚详细地回答了一点。第二部分(即
)是一个本地定义的新对象,由于它是表达式的最后一部分,因此基本上作为表达式的结果返回-希望有意义:\@FelixKling-doh…:\谢谢。更正:)