javaScript function - why my default argument fails?

前端 未结 3 2463
离开以前
离开以前 2021-02-20 08:20

My Javascript function leads my console to return me :

TypeError: style is null

Here the snippet:

相关标签:
3条回答
  • 2021-02-20 08:42

    Two things you need to update

    1. Passing default parameter either no value or undefined
    2. changing the style default variable into another name

    please see the updated code

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

    you can write the above snippet in much more cleaner way using es6

    see the below snippet

    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"))
    
    0 讨论(0)
  • 2021-02-20 09:05

    Rename your style variable into styles and then instead of having null as your first argument when you invoke styling, use 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]
    
    0 讨论(0)
  • 2021-02-20 09:06

    Default parameters is assigned only if no value or undefined is passed

    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 ?

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

    0 讨论(0)
提交回复
热议问题