JS参数默认值问题(js函数参数默认值)
背景知识
在 JS 中,使用下面这种形式可以给方法参数设置默认值,但是只支持两种情况:
不传该参数
传入值是
undefined
const foo = (arg = 'default') => console.log(arg)复制代码
其他 falsy
值不会使用默认值:
foo('') // '' (输出空字符串,引号是为了说明) foo(null) // null foo(false) // false foo(0) // 0复制代码
问题场景
所以单纯使用参数默认值,有时候会遇到参数类型错误的问题,比如:
// 场景1 const foo = (arg = () => {}) => { arg(); } foo(null) // Uncaught TypeError: arg is not a function // 场景2 const foo = (arg = {}) => { if (a.key) { // do sth... } } foo(null) // Uncaught ReferenceError: a is not defined复制代码
解决方案
在群里跟人讨论时,提出了如下几种方案:
const foo = (arg = 'default') => console.log(arg); // 方案1 axios(url, data).then((res) => { foo(res?.value); }) // 方案2 axios(url, data).then((res) => { foo(res.value ?? ''); }) // 方案3 axios(url, data).then((res) => { foo(res.value || undefined); })复制代码
以上几种方案能避免出现前面的问题场景,但是这几个方案都是从“使用者”的角度出发,这样以后在调用这个方法的时候,都需要按照这几种形式传值。
如果从方法的“创建者”的角度出发,可以使用以下方式:
const foo = (arg) => { arg = arg || 'default'; }复制代码
但是如果方法本身是需要接收 falsy
值的话,就不能使用这种形式了,需要自己注意区分使用场景,决定使用哪种形式。
如果你有其他更好的解决方案,欢迎留言分享。
作者:Wetoria
链接:https://juejin.cn/post/7047798933212364813