Web*_*man 11 javascript function default-parameters ecmascript-6
我的Javascript函数导致控制台返回我:
TypeError:样式为null
以下是代码段:
let style = {
one: 1,
two: 2,
three: 3
}
function styling(style = style, ...ruleSetStock) {
return ruleSetStock.map(ruleSet => {
console.log(ruleSet)
return style[ruleSet]
})
}
console.log(styling(null, "one", "two", "three"))Run Code Online (Sandbox Code Playgroud)
我不明白为什么。在我看来,一切都很好,
任何提示都会很棒,谢谢。
Cod*_*iac 10
仅当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"))Run Code Online (Sandbox Code Playgroud)
如果我想在所有类型上使用默认值
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"))Run Code Online (Sandbox Code Playgroud)