Alternatives of spread syntax

前端 未结 2 1904
梦谈多话
梦谈多话 2021-01-23 01:43

I see several uses of spread syntax in a code. For example:

function tree2table(tree) {
    var children = tree[\"children\"];
    if (children === undefined) re         


        
相关标签:
2条回答
  • 2021-01-23 02:12

    Differenz

    Array.prototype.push.apply(result, values) modifies instead of making a copy of an array

    Example

    const result = []
    const values = ['a', 'b']
    Array.prototype.push.apply(result, values)
    console.log(result)

    Solution

    function tree2table(tree) {
      var children = tree["children"];
      if (children === undefined) return [];
      var result = [];
      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        var link = [child["name"], tree["name"], child["size"]];
        result.push(link);
        Array.prototype.push.apply(result, tree2table(child))
      }
      return result
    }
    

    Compatible

    based on the version information

    Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards.

    0 讨论(0)
  • 2021-01-23 02:12

    You could use function#apply, which takes the parameters as array.

    The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

    Array.prototype.push.apply(result, tree2table(child));
    
    0 讨论(0)
提交回复
热议问题