ES6 Spread运算符到vanilla Javascript

问题描述 投票:4回答:2

我添加了一个脚本,该脚本使用ES6扩展运算符到从url获取params的项目。在我发现项目不支持ES6之后,不确定如何将其恢复为正常的vanilla Javascript语法。

使用普通的Javascript数组并使用扩展运算符很​​容易,但在像这样的更复杂的实例中,我无法使数组在不完全更改脚本的情况下返回结果。

getQueryURLParams("country");

getQueryURLParams = function(pName) {
    var urlObject = location.search
    .slice(1)
    .split('&')
    .map(p => p.split('='))
    .reduce((obj, pair) => {
      const [key, value] = pair.map(decodeURIComponent);

      return ({ ...obj, [key]: value }) //This is the section that needs to be Vanilla Javascript
    }, {});

    return urlObject[pName];
};

感谢大家的回复。在来回之后,我意识到我将整个脚本转换为ES5的建议是正确的,因为浏览器只抱怨该行,但其他项目不是ES5也是有问题的。

这是我使用ES5后的情况:

getQueryURLParams = function(pName) {


if (typeof Object.assign != 'function') {
    // Must be writable: true, enumerable: false, configurable: true
    Object.defineProperty(Object, "assign", {
      value: function assign(target, varArgs) { // .length of function is 2
        'use strict';
        if (target == null) { // TypeError if undefined or null
          throw new TypeError('Cannot convert undefined or null to object');
        }

        var to = Object(target);

        for (var index = 1; index < arguments.length; index++) {
          var nextSource = arguments[index];

          if (nextSource != null) { // Skip over if undefined or null
            for (var nextKey in nextSource) {
              // Avoid bugs when hasOwnProperty is shadowed
              if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                to[nextKey] = nextSource[nextKey];
              }
            }
          }
        }
        return to;
      },
      writable: true,
      configurable: true
    });
  }

var urlObject = location.search
.slice(1)
.split('&')
.map(function(element ) { 
    return element.split('='); 
})
.reduce(function(obj, pair) {  

  const key = pair.map(decodeURIComponent)[0];
  const value = pair.map(decodeURIComponent)[1];

  return Object.assign({}, obj, { [key]: value });
}, {});

return urlObject[pName];
};
javascript arrays ecmascript-6 spread-syntax ecmascript-2018
2个回答
8
投票

你可以使用Object.assign()

return Object.assign({}, obj, { [key]: value });

演示:

const obj = { a: 1 };
const key = 'b';
const value = 2;

console.log(Object.assign({}, obj, { [key]: value }));

FWIW,{ ...obj }语法被称为“Object Rest/Spread Properties”,它是ECMAScript 2018的一部分,而不是ECMAScript 6。


2
投票

既然你想要ES5的语法,那就是Object.assing()source: MDN)的polyfill

   

// we first set the Object.assign function to null to show that the polyfill works
Object.assign = null;

// start polyfill

if (typeof Object.assign != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

// end polyfill


   // example, to test the polyfill:

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

const object2 = Object.assign({c: 4, d: 5}, object1);

console.log(object2.c, object2.d);
// expected output: 3 5
© www.soinside.com 2019 - 2024. All rights reserved.