功能参数的默认值?

编程入门 行业动态 更新时间:2024-10-10 14:26:57
本文介绍了功能参数的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以,只要我记得,我一直这样做,但我很好奇这是否真的应该做的事情。你编写一个带参数的函数,所以你预计它有一个值,但如果没有,你有充分的理由将它默认为零。我目前所做的是编写辅助函数:

So I've been doing this for as long as I can remember, but I'm curious if this is really what I should be doing. You write a function that takes a parameter, so you anticipate it to have a value, but if it doesn't, you have a good reason to default it, to say zero. What I currently do is write a helper function:

function foo() { return foo(0); }; function foo(bar) { ... };

我刚跑过一个我做过这个的实例,我奇怪地看了几秒钟之前理解我背后的逻辑。我来自php,这是微不足道的:

I just ran across an instance where I did this and I looked at it oddly for a few seconds before understanding my logic behind it. I come from php where it's trivial:

function foo(bar=0) { ... }

是否有我不知道的javascript替代方案?

Is there a javascript alternative that I'm not aware of?

推荐答案

您不能在JavaScript中使用重载函数。相反,使用基于对象的初始化,或检查值并指定默认值(如果没有提供)。

You can't have overloaded functions in JavaScript. Instead, use object based initialization, or check for the values and assign a default if none supplied.

在您的示例中,第二个函数 foo( bar)将替换第一个。

In your example, the second function foo(bar) will replace the first one.

这是一个使用对象初始化的函数。

Here's a function using object initialization.

function foo(config) { extend(this, config); }

其中 extend 是将配置对象与当前对象合并的函数。它类似于jQuery中的 $ .extend 方法,或者MooTools的 $ extend 方法。

where extend is a function that merges the config object with the current object. It is similar to the $.extend method in jQuery, or $extend method of MooTools.

调用函数并传递命名键值对

Invoke the function and pass it named key value pairs

foo({ bar: 0 });

初始化的另一种方法是查看提供的值,如果值是,则指定默认值没有给出

The other way to initialize is to look at the supplied values, and assign a default if the value is not given

function foo(bar) { bar = bar || 0; }

只要bar不是假值,这就有效。所以 foo(false)或 foo()仍将初始化 bar 到 0 。对于这种情况,请进行明确检查。

This works as long as bar is not a falsy value. So foo(false) or foo("") will still initialize bar to 0. For such cases, do an explicit check.

function foo(bar) { bar = (typeof bar == 'undefined' ? 0 : bar); }

更多推荐

功能参数的默认值?

本文发布于:2023-06-02 19:32:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457434.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   参数   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!