javascript - 函数中的 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 ','
我们如何做到这一点?
解决方案
参数列表的顶层没有逗号,因此您需要传递一个参数,其结构如下:
{ 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 }});
推荐阅读
- dialogflow-es - 知识在“尝试”中起作用,但代理无法识别意图并检索 $Knowledge.Answer
- oracle - sqlplus 在从 shell 脚本执行时失败,但从终端执行时工作正常
- c# - ScrollIntoView 不会滚动到 DataGrid 中的 SelectedItem
- swift - 无法从连接到 XIB 的 UIView 执行 segue
- java - ClassLoader.getSystemClassLoader().getResourceAsStream 克隆项目后返回 null
- python - check_output 在 python 3.6 中不起作用,而 subprocess 工作正常
- javascript - 使用 localStorage 保存的复选框选择问题
- android - 在 Kotlin jackson ObjectMapper.readValue() 上导致 java.lang.IllegalStateException: readValue(content, jacksonTypeRef
()) 不能为空 - r - 如何将函数参数传递给 map_df()?
- javascript - 如何跟踪用户更改了 VueJS 数组中的哪些项目?