Backticks calling a function

后端 未结 2 1020
猫巷女王i
猫巷女王i 2020-11-22 06:41

I\'m not sure how to explain this, but when I run

console.log`1`

In google chrome, I get output like

console.log`1`
VM1238         


        
2条回答
  •  逝去的感伤
    2020-11-22 07:27

    Tagged template literal:

    The following syntax:

    function`your template ${foo}`;
    

    Is called the tagged template literal.


    The function which is called as a tagged template literal receives the its arguments in the following manner:

    function taggedTemplate(strings, arg1, arg2, arg3, arg4) {
      console.log(strings);
      console.log(arg1, arg2, arg3, arg4);
    }
    
    taggedTemplate`a${1}b${2}c${3}`;

    1. The first argument is an array of all the individual string characters
    2. The remaining argument correspond with the values of the variables which we receive via string interpolation. Notice in the example that there is no value for arg4 (because there are only 3 times string interpolation) and thus undefined is logged when we try to log arg4

    Using the rest parameter syntax:

    If we don't know beforehand how many times string interpolation will take place in the template string it is often useful to use the rest parameter syntax. This syntax stores the remaining arguments which the function receives into an array. For example:

    function taggedTemplate(strings, ...rest) {
      console.log(rest);
    }
    
    taggedTemplate `a${1}b${2}c${3}`;
    taggedTemplate `a${1}b${2}c${3}d${4}`;

提交回复
热议问题