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 函数中的默认参数值


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01