Object spread operator trow error in microsoft edge

你。 提交于 2020-08-10 05:47:11

问题


I have code:

let a = {a: 'a', b: 'b'};
let b = {c: 'c', d: 'd'};
let c = {...a, ...b};

In chrome/firefox/... its display: c = {a: 'a', b: 'b', c: 'c', d: 'd'}, but in microsoft edge its trow error Expected identifier, string or number.

I try to use cdn.polyfill.io and https://babeljs.io/docs/en/babel-polyfill but no luck.

What i can do to run my webpack code in microsoft edge?


回答1:


The { ...obj } syntax is called "Object Rest/Spread Properties" and it's a part of ECMAScript 2018 which is not supported by Edge Legacy. You can use Babel to transpile it.

If you just want to use it in non Node.js environments, you can use babel-standalone. You just need to load the babel-standalone in your script and write the script you want to transpile in script tag with type “text/babel” or “text/jsx”, the result in Edge Legacy will be {"a":"a","b":"b","c":"c","d":"d"}:

<!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">
        let a = { a: 'a', b: 'b' };
        let b = { c: 'c', d: 'd' };
        let c = { ...a, ...b };
        console.log(JSON.stringify(c));
    </script>
</body>
</html>



回答2:


It should be available in Edge since 79 without any transcompiler (like Babel) needed (but not IE, don't confuse them).

https://caniuse.com/#feat=mdn-javascript_operators_spread_spread_in_object_literals

That said you could in most situations just use Object.assign() instead if you want -

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Your code would then be:

let a = {a: 'a', b: 'b'};
let b = {c: 'c', d: 'd'};
let c = Object.assign(a,b)

console.log(c)

Object.assign() is supported since Edge 12:

https://caniuse.com/#feat=mdn-javascript_builtins_object_assign



来源:https://stackoverflow.com/questions/60651462/object-spread-operator-trow-error-in-microsoft-edge

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