JavaScript函数 - 为什么我的默认参数失效了?

10

我的JavaScript函数导致控制台返回:

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

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

有任何提示都将是极好的,谢谢。


默认函数参数 允许在未传递值或传递 undefined 的情况下,使用默认值初始化命名参数。” - adiga
1
问题在于你传递了 null,因此它会在返回行抛出 null 错误。如果它是 null,你想要使用默认的样式对象。 - Learner
3个回答

11

默认参数值只有在传递没有值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"))

如果我想对所有类型为假的值(如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. 传递默认参数,可以是没有值或未定义
  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"))

cleaner way using es6”是什么意思?显然,OP已经在使用默认的初始化语法中使用了ES6。您可能需要指出您认为使代码更清晰的特定语言功能。 - Bergi
删除return关键字 - Learner

0
将您的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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接