簡體   English   中英

Function 中的 ES6 解構

[英]ES6 Destructuring in Function

我正在嘗試在 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);
}

我知道這是一種解構方式,但我如何在調用此 function 時通過 arguments? 我試過這樣稱呼它

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 }});

function displaySummary的參數不是有效的Object

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

function 定義期望收到具有此形狀的 object

{ 
    name: "John Doe", 
    scores: { 
        maths = 0, 
        english = 0, 
        science = 0 
    } 
}

但是在您的通話中,您傳遞了一個沒有密鑰的 object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM