JavaScript函数中的默认参数值 [英] Default argument values in JavaScript functions

查看:98
本文介绍了JavaScript函数中的默认参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

使用默认值为参数指定一个javascript函数/ blockquote>



在PHP中:

 函数func($ a = 10,$ b = 20){
//如果不带参数调用func()$ a将为10,$ b将为20
}

如何在JavaScript中执行此操作?

如果我尝试在函数参数中赋值


缺少)在形式参数之后



解决方案

在JavaScript中,您可以调用一个没有参数的函数(即使它有参数)。

所以你可以添加如下默认值:

pre $函数func(a,b){
if(typeof(一)===未定义)A = 10;
if(typeof(b)==='undefined')b = 20;

//您的代码
}

然后您可以将它称为 func(); 以使用默认参数。



以下是测试:

 函数func(a,b){
if(typeof(a)==='undefined')a = 10;
if(typeof(b)==='undefined')b = 20;

alert(A:+ a +\\\
B:+ b);
}
//测试
func();
func(80);
func(100,200);


Possible Duplicate:
How do I make a default value for a parameter to a javascript function

in PHP:

function func($a = 10, $b = 20){
  // if func() is called with no arguments $a will be 10 and $ b  will be 20
}

How can you do this in JavaScript?

I get a error if I try to assign values in function arguments

missing ) after formal parameters

解决方案

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
}

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);

这篇关于JavaScript函数中的默认参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆