javaScript函数-为什么我的默认参数失败? [英] javaScript function - why my default argument fails?

查看:71
本文介绍了javaScript函数-为什么我的默认参数失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Javascript函数使我的控制台返回我:

My Javascript function leads my console to return me :


TypeError:样式为空

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

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

I can't understand why. It seems to me everything is great,

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

Any hint would be great, thanks.

推荐答案

默认参数 仅在无值未定义传递

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 )使用默认值怎么办?

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

这篇关于javaScript函数-为什么我的默认参数失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆