JavaScript---函数,基本介绍,函数写法,有无参数有无返回值函数。

一、函数写法

function 函数名(){

//函数体

}

var 变量名=function (){

//函数名

}

函数:封装性,把重复代码封装起来,一般这些代码都具有特殊用途。

函数是特殊的变量。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
	</head>
	<body>
		
		<script>
			
			// 函数:封装性,把重复代码封装起来,一般这些代码都具有特殊用途。
			// 定义函数
			// function 函数名(){
			// 	函数体
			// }

			function print(){
				console.log('hello');
				console.log('welcome');
			}
			// 调用函数:函数名() 执行函数体内部代码
			console.log(print())
			print();
		</script>
	</body>
</html>

二、函数的有参无参有返回值无返回值
    1、无参无返回值
    2、有参无返回值
    3、无参有返回值
    4、有参有返回值

案例: 1、无参无返回值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>无参无返回值</title>
	</head>
	<body>
		<script>
//			定义函数
//无参数
			function mine(){
				console.log('hello');
//无返回值
			}
			mine();
			
		</script>
	</body>
</html>

 2、有参无返回值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
//			函数名和变量名,命名规则一样?
//声明函数。形参,相当于声明变量。
function add(x,y){
	console.log(x+y);
	console.log(z);
}
//调用函数。实参。相当于给变量=赋值
add(1,2);
add(5,6);
add(5,6,7);//不会报错,实参数量可以大于形参的数量
add(1);//不会报错
//增加入z
add(5,6,7);
/*error:z is not defined*/

//还未定义变量a前打印
console.log(a);
/*error:a is not defined*/
var a;
console.log(a);
/*定义变量a后打印undefined*/

		</script>
	</body>
</html>

运行结果:

3、无参有返回值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			//函数名和变量名,命名规则一样
			function add(){
				console.log('i can');
				//如果函数有返回值,使用函数,得到的就是函数的return的值。
//				碰到return,终止函数的执行,一个函数中只能有一个return.
				return 'hello';
				return 'why not';
			}
			console.log(add());
//			控制台只能打印出来 hello, why no ,undefined;
//			只有 return 的时候才能打印出函数的结果,否则为undefined
		</script>
	</body>
</html>

4、有参有返回值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>有参有返回值</title>
	</head>
	<body>
		<!--有参有返回值-->
		<script type="text/javascript">
//			定义变量
			function text(x,y,z){
//				返回值
				return x+y+z;
			}
//			给变量赋值,并得到返回值
			console.log(text(1,2,3));
			document.write(text(1,2,4));
			document.write('<br>');//br这些标签是常量,要用引号括起来。
			document.write(text(44,5,5));
		</script>
	</body>
</html>

 

猜你喜欢

转载自blog.csdn.net/weixin_41544553/article/details/86589034
今日推荐