javaScript function - why my default argument fails?

前端 未结 3 2407
离开以前
离开以前 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"))
    

提交回复
热议问题