Alternatives of spread syntax

依然范特西╮ 提交于 2019-12-24 11:04:06

问题


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

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
}

However, spread syntax is not supported in IE. Does anyone know what is the best way to change result.push(...tree2table(child)) such that it becomes cross-browser and as efficient as before?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/45838170/alternatives-of-spread-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!