传播语法的替代方案

Alternatives of spread syntax

我在一段代码中看到了 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)) 以使其成为跨浏览器并像以前一样高效的最佳方法是什么?

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

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));

差异

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

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.