JavaScript function in the arguments object

JavaScript function in the arguments object

A, arguments concept

在JavaScript中,参数在函数内部是以一个数组表示的,函数接受的永远是一个数组
arguments是函数内部的一个专门用来存储实参的数组对象

Two, arguments features

1.arguments对象和Function是分不开的
2.arguments对象不能显式创建
3.arguments对象只有函数开始时才可用

Three, arguments methods

arguments.callee    //自己,arguments所在的函数,指向当前执行的函数。
arguments.caller    //指向调用当前函数的函数
arguments.length    //获得长度,实参的个数
arguments[i]        //通过遍历索引,获得每个实参

1.arguments objects

function fn(a,b,c){
    console.log(arguments);//输出内容见下图
    return a+b+c;
}
console.log(fn(1,2,3));    //输出6

2.arguments.callee

function fn(a,b,c){
    console.log(arguments.callee);//输出当前函数本身,见下图
    return a+b+c;
}
console.log(fn(1,2,3));    //输出6

3.arguments.length

function fn(a,b,c){
    console.log(arguments.length);//输出3---当前arguments的长度
    return a+b+c;
}
console.log(fn(1,2,3));    //输出6

4.arguments[]

1) Output Parameters

function fn(a,b,c){
    for(var i=0;i<arguments.length;i++){
        console.log(arguments[i]);//依次输出1,2,3
    }
    return a+b+c;
}
console.log(fn(1,2,3));    //输出6

2) setting parameters

function fn(a,b,c){
    arguments[0] = "hello";//参数也可被设置
    for(var i=0;i<arguments.length;i++){
        console.log(arguments[i]);//依次输出  hello,2,3
    }
    return a+b+c;
}
console.log(fn(1,2,3));    //输出hello23---三个值通过+号转为字符串进行连接

5.arguments Notes

//在函数中只要是实参全都传给arguments
//在函数中,形参和实参的个数,可以为任意个,甚至数量不对应,程序都不会报错,但是在计算过程中可能会出现NaN
function fn(a,b,c){
    return a+b+c;
}
console.log(fn(1,2));    //输出NaN---因为形参c没有接收到数据,但在进行运算时用到了形参c

Four, arguments turn array

arguments object is not a true array, which is similar to an array, but in addition to the length property and does not have any elements other than the index array property. For example, it does not pop method. But it can be converted to a real array , the array is converted to true after you can use the full array method

function fn(a, b, c) {
    arguments[0] = "hello"; //参数也可被设置
    var args = Array.from(arguments);//进行转数组操作
    console.log(args);//结果见下图,输出的是一个数组
    return a + b + c;
}
console.log(fn(1, 2, 3)); //输出hello23---通过+号字符串拼接

Guess you like

Origin www.cnblogs.com/zhupengcheng/p/11601352.html