Home  >  Article  >  Web Front-end  >  Interesting questions in JavaScript: Mapping of formal parameters and actual parameters

Interesting questions in JavaScript: Mapping of formal parameters and actual parameters

黄舟
黄舟Original
2017-01-22 14:55:572018browse

As an extension to the function function, you need to establish a correct mapping relationship between its formal parameters and actual parameters when a function is called.

Let’s look at the following example first:

function func1(arg1, arg2) { ... }  
  
var map = createArgumentMap(func1,'valueOfArg1', 'valueOfArg2');  
console.log(map['arg1']);  // writes 'valueOfArg1'  
console.log(map['arg2']);  // writes 'valueOfArg2'

This mapping function receives a function object as the first parameter, and an actual parameter list of unknown length. You have to specify it in the form of this function object. Establish a mapping between parameters and actual parameter lists, represent them as an associative array, and return them.

The order of actual parameter list and function parameter definition is the same, and they are all valid and legal parameters.

This topic is to establish the mapping between formal parameters and actual parameters. Then, we first obtain the toString() string form of the function object and intercept its formal parameter list.

Next, because the length of the actual parameter list is unknown, use the Array.prototype.slice method, set its context to the arguments object, intercept the actual parameters starting from index 1, and obtain the array form of the actual parameter list.

Finally, based on the actual parameter list, establish an associative array, with the formal parameter as key and the actual parameter as value, and return the associative array.

In this way, the parameter mapping function is completed.

String.prototype.trim = function(){    
  return this.replace(/(^\s*)|(\s*$)/g, "");    
};  
  
var findArgs = function(funcStr){    
    var bracket1 = funcStr.indexOf("(");    
    var bracket2 = funcStr.indexOf(")");    
    var argsStr = funcStr.slice(bracket1+1,bracket2);    
    var args = argsStr.split(",");    
    return args.map(function(e){    
        return e.trim();    
    });    
};   
  
function createArgumentMap(func) {  
    var args = findArgs(func.toString());  
    var realArgs = Array.prototype.slice.call(arguments,1);  
    var map = {};  
    for(var i=0;i<realArgs.length;i++){  
        map[args[i]] = realArgs[i];  
    }  
    return map;  
}

The above is the content of interesting JavaScript questions: the mapping of formal parameters and actual parameters. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn