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

时间:2019-06-02 18:15:40

标签: javascript function ecmascript-6 default-parameters

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

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

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

3 个答案:

答案 0 :(得分:10)

Default parameters仅在通过no valueundefined的情况下分配

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)

您需要更新两件事

  1. 传递默认值(无值或未定义)
  2. 将样式默认变量更改为另一个名称

请查看更新的代码

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]