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

javaScript function - why my default argument fails?

我的 Javascript 功能将我的控制台引导至 return 我 :

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

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

任何提示都很好, 谢谢。

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

What if i want to use default value on all sorts of 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. 传递默认参数没有值或未定义
  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"))

将您的 style 变量重命名为 styles,然后在调用 styling 时不要将 null 作为第一个参数,而是使用 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]