3 回答
TA贡献1831条经验 获得超4个赞
仅当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"))
TA贡献1859条经验 获得超6个赞
你需要更新的两件事
传递默认参数没有值或未定义
将样式默认变量更改为另一个名称
请查看更新后的代码
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"))
TA贡献2012条经验 获得超12个赞
将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]
添加回答
举报