JavaScript之函数

函数:将一些可重复使用的并且有特殊功能的代码封装起来。函数具有封装性。
定义函数:function 函数名(参数1,参数2,...){函数体}
使用函数:函数名(参数); 使用函数,即执行函数体中的代码

一、函数定义

(1)普通定义方法
 function add(x,y){
 console.log(x+y);
}
 add(10,20);

(2)匿名函数
var a=function(){
console.log('A');
}
a();

(3)变量定义方法。不推荐使用。
var sum=new Function('x','y','console.log(x+y)');
sum(4,5);

二、arguments对象

function add(x,y,z){
// 定义函数时,传递的参数为形式参数,称为形参,相当于声明变量
console.log(arguments);
// arguments 得到的是使用函数时传递的实参,是一个数组
console.log(arguments[0]);
// arguments[0]获取第一个实参
console.log(arguments[arguments.length-1]);
// arguments.length 获取实参的个数,arguments[arguments.length-1]获取最后一个实参
console.log(add.length);
// 函数名.length获取形参的个数
if(add.length==arguments.length){
// 传递数据
}else{

}
}
add(2,3);
// 使用函数,传递的参数为实际参数,称为实参,相当于给变量赋值

三、函数类型

(1)无参无返回值
function add(){
console.log('hello');
}

(2)有参无返回值
function add(x,y){
// console.log(x+y);
x+y;
}

(3)无参有返回值
function add(){
var a=10;
var b=20;
console.log(b);
return a+b;
// 使用函数,最终得到的是return中的值,函数遇到return会终止执行,如果没return,浏览器编译时自动加上return,但返回的值为空
console.log(a);
}

(4)有参有返回值
function add1(x,y){
return x+y;
}

四、函数作用域

在JavaScript中,只有函数的作用域,即除了在函数中声明的变量,其他的都是全局变量

案例:

var a=10;
console.log(a);
function fn(){
var b=20;
console.log(a);
console.log(b);
}
fn();
// console.log(b);
for(var i=0;i<10;i++){
// console.log(i);
}
while (a==10) {
a++;
var c=100;
console.log(c);
}

console.log('i:'+i);
console.log(c);

 

posted @ 2019-09-16 14:00  陌漠  Views(115)  Comments(0Edit  收藏  举报