简体   繁体   English

JavaScript(ES6):命名参数和默认值

[英]JavaScript (ES6): Named parameters and default values

Coming from Python and really liking the way to set named parameters and default values - now it seems that ES6 allows me to do similar. 来自Python并且非常喜欢设置命名参数和默认值的方式 - 现在似乎ES6允许我做类似的事情。 But I can't see why this last call breaks: 但我不明白为什么这最后一次电话会打破:

fun = ({first=1, last=1}) => (1*first+2*last)

console.log("-----------")

console.log( fun({first:1, last:2}) )

console.log("-----------")

console.log( fun({last:1, first:2}) )

console.log("-----------")

console.log( fun() ) // Breaks

You need a default object. 您需要一个默认对象。

 var fun = ({ first = 1, last = 1 } = {}) => 1 * first + 2 * last; // ^^^^ console.log(fun({ first: 1, last: 2 })); console.log(fun({ last: 1, first: 2 })); console.log(fun()); 

因为你需要一个可以解构的对象:

fun({})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM