如何在IE 11中实现展开运算符?

How to achieve the spread operator in IE 11?

对于某些“提取”操作,我试图在不使用扩展运算符的情况下使以下代码片段正常工作,因为 IE 11 不了解扩展运算符。

适用于 Chrome,但不适用于 IE 11:

html_col_width =[{"targets":0, "width":50}, {"targets":1, "width":100},{"targets":2, "width":442}]

        ... some other code
        order: [
            [response.order_by_column, response.order_by]
        ],
        columnDefs: [
                      ...html_col_width,
                      {other: stuff},
                      {other: stuff}
    })

参见列定义:...html_col_width

如果没有扩展运算符,我如何实现以下目标:

columnDefs: [
          {"targets":0, "width":50},
          {"targets":1, "width":100},
          {"targets":2, "width":442},
          {other: stuff},
          {other: stuff}
    })

我已阅读并尝试了以下内容,但如果对象数组包含 2 个键,则此方法无效:。所提供的link处的内容是关于合并个不同的对象,这使得问题相当不同。

您使用的是“数组解构”:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

如您所说,它在 IE 中不起作用,那是因为它是 ES6 的一部分,而 IE 11 不支持(而且永远不会支持)。

解决它的一个选择是使用像 Babel 这样的转译器。

其他选项,就是定义你自己的函数:

var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
        r[k] = a[j];
return r;

};

var html_col_width = [{ "targets": 0, "width": 50 }, { "targets": 1, "width": 100 }, { "targets": 2, "width": 442 }];
var columnDefs = __spreadArrays(html_col_width, [{ other: 'stuff' }, { other: 'stuff' }]);

你试过了吗concat()

html_col_width =[{"targets":0, "width":50}, {"targets":1, "width":100}, {"targets":2, "width":442}]

obj = {
  columnDefs: [
    {other: 'sds'},
    {others: 'dds'}
    ]
};

obj.columnDefs = obj.columnDefs.concat(html_col_width);
console.log(obj.columnDefs);

Spread properties is a part of ECMAScript 2018 which is not supported by IE. You can use Babel 转译它。

如果只想在非Node.js环境下使用,可以使用babel-standalone。您只需要在脚本中加载 babel-standalone 并在脚本标签中写入您要转译的脚本,类型为“text/babel”或“text/jsx”,例如:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.1/babel.min.js"></script>
</head>
<body>
    <script type="text/babel">
        var html_col_width =[{"targets":0, "width":50}, {"targets":1, "width":100},{"targets":2, "width":442}];
        var columnDefs = [
        ...html_col_width,
        { other: "stuff" },
        { other: "stuff" }
        ];
        console.log(JSON.stringify(columnDefs));
    </script>
</body>
</html>

IE 中的结果: