ES6将运算符扩展为原始Javascript

时间:2018-09-16 18:38:31

标签: javascript arrays ecmascript-6 spread-syntax ecmascript-2018

我已经添加了一个脚本,该脚本使用ES6传播运算符到从URL获取参数的项目中。我发现该项目不支持ES6后,不确定如何将其恢复为普通的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];
};

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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