【JS】Five minutes to understand arguments

1. There are implicit arguments in each function, which is the list of arguments we commonly use, which is why we can call it in the function body. At the same time, the arguments object will be created only when the function is called, and its value will be null when it is not called.

function sum(){
    // arguments [1,2,3]
    var result = 0;
    for(var i = 0;i < arguments.length;i++{
         result += arguments[i];
     }
     console.log(result);
 }
sum(1,2,3);

2. When we output arguments in the console, we will find that arguments are not an array, but an array-like object.

3. When you assign a value to the formal parameters in the function body, you will find that the arguments will also change, indicating that there is a mapping relationship between the two.

function sum(a,b,c){
    //arguments [1,2,3]
    //var a = 1;
    //var b = 2;
    //var c = 3;
    a=2;
    var result = 0;
    console.log(arguments[0])
    for(var i=0; i<arguments.length;i++){
          result+=arguments[i];
    }
    console.log(result);
}
sum(1,2,3)
/*
   2
   7
*/    

4. The role of arguments.callee Before I talk about this, I want to talk about caller first, and talk about arguments.caller at the same time

   The caller of a function, when a function calls another function, the called function implicitly generates a caller attribute, which stores the function object that called it.

function oCall() {  
   console.log(oCall.caller);  
}  
  
function oCaller() {  
   oCall();  
}          
oCaller();

  arguments.caller feels useless, but is not available in strict mode and throws an error.

  arguments.callee is also unavailable in strict mode. It points to the function object that owns the arguments, which is oCall in the following example. In certain cases, when we don't want to use the function name of oCall, we can use the arguments.callee property instead. Example: call in setTimeOut

function oCall(a) {  
    console.log(arguments.callee);
}  
  
function oCallee(a) {  
    oCall();  
}  

5. The difference and usage of arguments and parameters, as well as the difference in use in es6, can be viewed at the following link, and I will add it when I have time in the future.

https://www.smashingmagazine.com/2016/07/how-to-use-arguments-and-parameters-in-ecmascript-6/


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325641053&siteId=291194637