Spread element magically turns functions into 'not functions'

前端 未结 4 901
北恋
北恋 2021-01-07 23:37

Suppose I have this simple JavaScript function:

function returnArray(){
    return [1, 2, 3];
}

Further suppose that I then say

<         


        
4条回答
  •  萌比男神i
    2021-01-08 00:14

    Just a minor change:

    function double(array) {
      // note the return here is an array, not a number
      if (array.length === 1) return [2 * array[0]];
    
      var [num, ...rest] = array;
      if (rest.length) return [2 * num, ...double(rest)];
    }
    
    console.log(double([1, 2, 3, 4]));

    You were returning a number, and destructuring a number will leave you with an error.

    ...5 // throws SyntaxError
    

提交回复
热议问题