【问题标题】:Alternatives of spread syntax扩展语法的替代方案
【发布时间】:2018-01-31 22:51:15
【问题描述】:

我在代码中看到了spread syntax 的几种用法。例如:

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);
        result.push(...tree2table(child))
    }
    return result
}

但是,IE 不支持扩展语法。有谁知道更改result.push(...tree2table(child)) 使其成为跨浏览器并像以前一样高效的最佳方法是什么?

【问题讨论】:

    标签: javascript arrays cross-browser spread-syntax


    【解决方案1】:

    您可以使用function#apply,它将参数作为数组。

    apply() 方法调用具有给定this 值的函数,arguments 作为数组(或类似数组的对象)提供。

    Array.prototype.push.apply(result, tree2table(child));
    

    【讨论】:

    • 嗨尼娜。这很有帮助!如何替换 return [...new Set(array.map(item =&gt; item[prop]))]; 之类的集合中的扩展运算符?
    • @Mike,你为什么要那样做? Set 仅在传播语法也可用的情况下可用。
    【解决方案2】:

    区别

    Array.prototype.push.apply(result, values) 修改而不是复制数组

    示例

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

    解决方案

    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
    }
    

    兼容

    基于version information

    支持以下文档模式:Quirks、Internet Explorer 6 标准、Internet Explorer 7 标准、Internet Explorer 8 标准、Internet Explorer 9 标准、Internet Explorer 10 标准、Internet Explorer 11 标准。

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 1970-01-01
      • 2013-07-09
      • 2016-06-04
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多