Default argument values in JavaScript functions(JavaScript 函数中的默认参数值)
问题描述
可能重复:
我该怎么做javascript函数参数的默认值
在 PHP 中:
function func($a = 10, $b = 20){
// if func() is called with no arguments $a will be 10 and $ b will be 20
}
如何在 JavaScript 中做到这一点?
How can you do this in JavaScript?
如果我尝试在函数参数中赋值,我会收到错误
I get a error if I try to assign values in function arguments
形式参数后缺少)
推荐答案
在javascript中你可以调用一个没有参数的函数(即使它有参数).
In javascript you can call a function (even if it has parameters) without parameters.
所以你可以像这样添加默认值:
So you can add default values like this:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
//your code
}
然后你可以像 func(); 一样调用它来使用默认参数.
and then you can call it like func(); to use default parameters.
这是一个测试:
function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;
alert("A: "+a+"
B: "+b);
}
//testing
func();
func(80);
func(100,200);
这篇关于JavaScript 函数中的默认参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 函数中的默认参数值
基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
