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

我的 Javascript 函数引导我的控制台返回我:


类型错误:样式为空


这里的片段:


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

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


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


千万里不及你
浏览 177回答 3
3回答

慕容708150

仅当no value或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"))如果我想在各种类型上使用默认值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"))

慕丝7291255

你需要更新的两件事传递默认参数没有值或未定义将样式默认变量更改为另一个名称请查看更新后的代码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,然后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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript