我的Javascript函数使控制台返回我:
TypeError:样式为空
以下是代码段:
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"))
我不明白为什么。在我看来,一切都很好,
任何提示都会很棒, 谢谢。
答案 0 :(得分:10)
Default parameters仅在通过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"))
答案 1 :(得分:1)
您需要更新两件事
请查看更新的代码
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"))
答案 2 :(得分:0)
将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]