-
慕容708150
仅当no value或undefined被传递时才分配默认参数let defaultStyle = { one: 1, two: 2, three: 3 }function styling(style = defaultStyle, ...ruleSetStock) { return ruleSetStock.map(ruleSet => { return style[ruleSet] })}console.log(styling(undefined, "one", "two", "three"))如果我想在各种类型上使用默认值falsy values such as false, '', null 怎么办?您不能为此使用默认参数,但可以使用 ||let style1 = { one: 1, two: 2, three: 3 }function styling(style, ...ruleSetStock) { style = style || style1 return ruleSetStock.map(ruleSet => { return style[ruleSet] })}console.log(styling(undefined, "one", "two", "three"))console.log(styling(null, "one", "two", "three"))console.log(styling('', "one", "two", "three"))console.log(styling(0, "one", "two", "three"))
-
慕丝7291255
你需要更新的两件事传递默认参数没有值或未定义将样式默认变量更改为另一个名称请查看更新后的代码let defaultStyle = { one: 1, two: 2, three: 3}function styling(style = defaultStyle, ...ruleSetStock) { return ruleSetStock.map(ruleSet => { console.log(ruleSet) return style[ruleSet] })}console.log(styling(undefined, "one", "two", "three"))您可以使用 es6 以更简洁的方式编写上述代码段见下面的片段const defaultStyle = { one: 1, two: 2, three: 3}const styling = (style = defaultStyle, ...ruleSetStock) => ruleSetStock.map(ruleSet => { return style[ruleSet]})console.log(styling(undefined, "one", "two", "three"))
-
繁花如伊
将style变量重命名为styles,然后null在调用时将其作为第一个参数,而不要styling使用undefined:const styles = { one: 1, two: 2, three: 3}function styling(style = styles, ...ruleSetStock) { return ruleSetStock.map(ruleSet => { console.log(ruleSet) return style[ruleSet] })}console.log(styling(undefined, "one", "two", "three"))// one// two// three// [1, 2, 3]