JavaScript 之 function函数及参数arguments

JavaScript用function关键字声明函数,可以用return返回值,也可以没有返回值。

建议:要么统一有返回值,要么统一都没有返回值,这样调试代码方便。

函数定义格式:

function functionName(参数){
//函数体内
}

定义函数的时候,参数可以写,也可以不写,Javascript没有限制传递参数的个数,也不介意传入参数的数据类型。

在函数体内可以通过arguments 对象来访问参数数组,从而获取传递给函数的每一个参数。

arguments.length:参数个数

用方括号语法访问它的每一个参数。例如arguments[0]为传进来的第一个参数。

function test(){
    console.log("======");
    console.log('agruments类型:'+typeof(arguments))
    console.log("====for...in读参数为====");
    for(var each in arguments){
        console.log(arguments[each]);
    }
    console.log("====for读参数为====");
    for(var i=0;i< arguments.length;i++){
        console.log(arguments[i]);
    }
    console.log("===arguments.length===");
    console.log(arguments.length)
}
test('a',20);

运行结果:

arguments的值永远与对应命名参数的值保持同步,前提是传入参数和命名参数一致。

示例:

function test(name,age){
    console.log('传进的age='+age)
    arguments[1]=50;
    console.log('给agruments[1]赋值后的age='+age)
}
test('line',20);

运行结果:

从运行结果发现,

arguments[1]的值与age的值是同步的

注意:所有参数传递的都只是值,不可能通过引用传递参数。


如果传入参数少于命名参数,示例如下
function test(name,age){
    console.log('传进的age='+age)
    arguments[1]=50;
    console.log('给agruments[1]赋值后的age='+age)
    console.log('给agruments[1]赋值后的arguments[1]='+arguments[1])
}
test('line');
 
运行结果如下:

从运行结果看出:
如果传入参数少于命名参数,那命名参数与arguments是不会同步的
 

猜你喜欢

转载自www.cnblogs.com/greenteaone/p/9225337.html