javaScript函数-为什么我的默认参数失败?

javaScript函数-为什么我的默认参数失败?

问题描述:

我的Javascript函数使我的控制台返回我:

My Javascript function leads my console to return me :


TypeError:样式为空

TypeError: style is 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"))

我不明白为什么。在我看来,一切都很棒,

I can't understand why. It seems to me everything is great,

任何提示都会很棒,
谢谢。

Any hint would be great, thanks.

默认参数 仅在无值未定义传递

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"))


如果我想对所有虚假值(例如false,'',null )使用默认值怎么办?

What if i want to use default value on all sorts of falsy values such as false, '', null ?

您不能为此使用默认参数,但是可以使用 ||

You can't use default parameter for that but you can use ||

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"))