下面给大家介绍javascript函数
函数的基本语法是:
function functionName(arg0,arg1,...,argN) { statements }
下面是个示例:
function str(name,age){ document.write(\"hello my name is \" + name + \". and i am \" + age + \" years old.\"); } str(\" oliver\",23); //hello my name is oliver. and i am 23 years old.
另外,任何函数在任何时候都可以通过return 语句后跟要返回的值来实现返回值。如:
function sum(num1,num2){ return num1 + num2; alert(\"hello\"); //返回return 之后不会继续执行alert } var result = sum(321,32); document.write(result); //353
因为执行完return 语句之后停止并立即退出,所以位于return 语句之后的任何代码都不会执行。
当然,一个函数可以包含多个return 语句。如:
function conp(a,b){ if (a > b){ return a; }else if (a == b){ return \"equal\"; }else{ return b; } } var result = conp(4,4); document.write(result); //equal var result = conp(321,4); document.write(result); //321
另外,return 语句也可以不带有任何返回值。这样,就可以立即停止函数执行并且返回undefined。如:
function conp(a,b){ if (a > b){ return; document.write(\"bad\"); }else{ document.write(b); } } var a = conp(33,3); document.write(a); //返回undefined 且不会出现\"bad\"
函数的参数
ECMAScript 函数的参数可以是任意多个,也可以是任何数据类型。它在函数体内可以通过arguments 对象来访问,如第一个参数是arguments[0]、第二个是arguments[1]等等。命名的参数只是提供了便利,但不是必须的。如:
function greeting(){ document.write(\"hello \" + arguments[0] + \". you look \" + arguments[1] + \".\"); } greeting(\"oliver\",\"good\"); //hello oliver. you look good.
另外,可以通过访问arguments 对象的length 属性,获得有多少参数传递给了函数。如:
function countArguments(){ document.write(\"there are \" + arguments.length + \" arguments here.\"); } countArguments(321,321,32,32); //there are 4 arguments here.
可以利用这一点与if 语句结合做判断。如:
function count(){ if (arguments.length == 1){ document.write(\"you just have 1 arguments.\"); }else{ document.write(\"you have many arguments.\"); } } count(321,321,321) //you have many arguments.
另外,arguments[] 可以与命名参数一起使用。
函数的重载(没有重载)
如果定义了两个名字相同的参数,则改名字只属于后定义的函数。如:
function add(){ document.write(arguments[0] + arguments[1]); } function add(){ document.write(arguments[0] + 100); } add(321,2); //421 不会执行第一个函数(两个参数相加),只执行最后一个同名的函数(第一个参数加上100)
PS:JavaScript匿名函数
函数是JavaScript中最灵活的一种对象,这里只是讲解其匿名函数的用途。匿名函数:就是没有函数名的函数。
1.1 函数的定义,首先简单介绍一下函数的定义,大致可分为三种方式
第一种:这也是最常规的一种
function double(x){ return 2 * x; }
第二种:这种方法使用了Function构造函数,把参数列表和函数体都作为字符串,很不方便,不建议使用。
第三种:
注意“=”右边的函数就是一个匿名函数,创造完毕函数后,又将该函数赋给了变量square。
1.2 匿名函数的创建
第一种方式:就是上面所讲的定义square函数,这也是最常用的方式之一。
第二种方式:
(function(x, y){ alert(x + y); })(2, 3);
这里创建了一个匿名函数(在第一个括号内),第二个括号用于调用该匿名函数,并传入参数。
本文地址:https://www.stayed.cn/item/20414
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我