我有一个函数,参数是 bar
有一个默认参数。""
. 如何覆盖 bar
的默认参数,值为 undefined
?
const foo = (bar = "") => {
console.log(bar)
}
foo(null) // null
foo(undefined) // "" <-- I want this to log `undefined`
如果用默认参数无法实现,那么写出 foo
来实现这个目标?
怎样写才是合适的呢?
foo
来实现这个目标?
如果你的意思是只有在没有参数传递给函数调用的时候才会默认,那么你需要检查 arguments
长度,如果你想保留一个箭头函数,也可以分散参数。
const foo = (...args) => {
const bar = args.length ? args[0] : "";
console.log(bar)
}
foo(null) // null
foo(undefined) // undefined
foo(); // ""
你遇到了JavaScript的 "两个空 "的有趣演示。null
和 undefined
.
null
是 指定的空值
undefined
是 毫无价值
你问的是关于 "值 "的传递 undefined
但这个前提是有缺陷的。有 是不 价值 undefined
- undefined
就是缺少一个值。
因此,你不应该通过 undefined
作为一个有意义的值来被函数解释。我的意思是,你可以这样做,但从JavaScript的角度来看,这相当于将 毫无 - 所以你是在和语言的设计作对,会遇到这样的问题。
如果你想传递一个有意义的、有目的的空值,那就是 null
是为了。
也许是因为你不能。这也是默认参数被设计成可以防止 undefined
值。
根据Mozilla 文件
缺省函数参数允许在没有传递值或未定义的情况下用默认值初始化命名的参数。
见上文。上面写得很清楚:如果 undefined
是通过。default
的参数。
非常的 定义 默认参数的初始化为无值或 未定义 的值。
所以,你应该删除默认参数,并在函数中添加一个条件检查(参见Kaiido的回答)。否则,你无法区分foo(undefined)和foo()。
如果你想让foo(undefined)和foo()都记录为undefined,你可以简单地删除默认参数
给出这个方法(typecript,抱歉我以为es6也是类似的)。
private static Foo(test: string, bar?: string): void
{
let args = arguments && arguments.length ? arguments.length : 0;
console.log(test, {
bar: bar,
type: typeof bar,
isUndefined: bar === undefined,
arguments: args,
value: (bar === undefined && args == 2) ? undefined : (bar === null && args == 2) ? null : bar ? bar : ""
});
}
用这个方法调用:
let u;
let v = undefined;
this.Foo("no parameter");
this.Foo("null", null);
this.Foo("empty", "");
this.Foo("non-empty", "non-empty");
this.Foo("undefined", undefined);
this.Foo("undefined parameter", u);
this.Foo("parameter with value of undefined", v);
我们得到这些结果:
no parameter
{bar: undefined, type: "undefined", isUndefined: true, arguments: 1, value: ""}
null
{bar: null, type: "object", isUndefined: false, arguments: 2, value: null}
empty
{bar: "", type: "string", isUndefined: false, arguments: 2, value: ""}
non-empty
{bar: "non-empty", type: "string", isUndefined: false, arguments: 2, value: "non-empty"}
undefined
{bar: undefined, type: "undefined", isUndefined: true, arguments: 2, value: undefined}
undefined parameter
{bar: undefined, type: "undefined", isUndefined: true, arguments: 2, value: undefined}
parameter with value of undefined
{bar: undefined, type: "undefined", isUndefined: true, arguments: 2, value: undefined}
因此,我们可以看到,我们无法区分一个未定义的变量 和一个包含未定义值的变量之间的区别。
通过观察参数的数量,我们可以判断是否缺少一个参数,然后判断它是否正好是(===)undefined或null。
const foo = (bar) => {
console.log(bar)
}
foo(null) // null
foo(undefined) // "" <-- i want this to log`undefined`
赋值 undefined
而不是空字符串,你会得到你所期望的输出。
const foo = bar => {
console.log(bar)
}
foo(null) // null
foo(undefined) // "" <-- i want this to log`undefined`
应该去掉默认参数,得到未定义。