3 回答

TA貢獻1831條經(jīng)驗 獲得超4個贊
僅當no value或undefined被傳遞時才分配默認參數(shù)
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 怎么辦?
您不能為此使用默認參數(shù),但可以使用 ||
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條經(jīng)驗 獲得超6個贊
你需要更新的兩件事
傳遞默認參數(shù)沒有值或未定義
將樣式默認變量更改為另一個名稱
請查看更新后的代碼
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條經(jīng)驗 獲得超12個贊
將style變量重命名為styles,然后null在調(diào)用時將其作為第一個參數(shù),而不要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]
添加回答
舉報