首页 > 解决方案 > 函数中的 ES6 解构

问题描述

我正在尝试学习 ES6 引入的 Javascript 中的解构。在关注中型帖子时,我遇到了以下代码:

function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } }) {
    console.log('Hello, ' + name);
    console.log('Your Maths score is ' + maths);
    console.log('Your English score is ' + english);
    console.log('Your Science score is ' + science);
}

我知道这是一种解构方式,但是如何在调用此函数时传递参数?我试过这样称呼它

displaySummary({'John Doe',{1,2,3}});

但是出现了类似的错误Uncaught SyntaxError: Unexpected Token ','

我们如何做到这一点?

标签: javascriptecmascript-6

解决方案


参数列表的顶层没有逗号,因此您需要传递一个参数,其结构如下:

{ name, scores: { maths = 0, english = 0, science = 0 } }

除了用:s 代替=s。所以:

function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } }) {
    console.log('Hello, ' + name);
    console.log('Your Maths score is ' + maths);
    console.log('Your English score is ' + english);
    console.log('Your Science score is ' + science);
}


displaySummary({ name: 'bob', scores: { maths: 95 }});


推荐阅读