javascript ES6用参数进行破坏

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript ES6用参数进行破坏相关的知识,希望对你有一定的参考价值。

// instead:
function myFunction(config) {
  console.log(config.text, config.line, config.truncate);
}

// we can do:
function myFunction({ text, line, truncate, extra = 'super!', foo: superExtra = 'wow' } = {}) {
  console.log(text, line, truncate, extra, superExtra); // Some value 0 100 super! wow
}
// The `= {}` it's a fallback object in case you didn't pass any. Lets you call the function without any parameters.

//usage for both examples:
myFunction({
  text: "Some value",
  line: 0,
  truncate: 100
});


// most advanced case:
const student = {
  name: 'John Doe',
  age: 16,
  scores: {
    maths: 74,
    english: 63,
    science: 85
  }
};

function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } = {} } = {}) {
 // some code
}


以上是关于javascript ES6用参数进行破坏的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript ES6 - 函数扩展

JavaScript ES6 - 函数扩展

打字稿和嵌套解构

JavaScript中一个对象中的默认破坏函数参数

ES6---JavaScript

javascript ES6 - 休息参数