【问题标题】:ES6 Spread operator to vanilla JavascriptES6传播运算符到香草Javascript
【发布时间】:2019-02-20 18:15:26
【问题描述】:

我已将使用 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];
};

【问题讨论】:

  • ES6 === 香草。你是说 ES5 吗?
  • 另外,如果是 ES5,箭头函数也应该去掉。

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


【解决方案1】:

你可以使用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。

【讨论】:

  • Object.assign 是 ES6
  • @Jonathan 是的,但是 OP 正在使用其他 ES6 功能,例如箭头函数和计算属性名称,所以我认为问题仅出在对象扩展属性上,浏览器并不广泛支持.
【解决方案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

【讨论】:

  • 你为什么要做Object.assign = null; 然后立即检查它是否是一个函数?检查将类似于:“这是null,呵呵!”.
  • 这是首先检查它的 polyfill 的一部分。出于演示目的,我将其设置为 null 以表明 polyfill 确实有效
  • 您可能需要添加说明,这样人们就不会从字面上理解它,而只是覆盖可能已经存在的Object.assign。旁边的一行注释就完美了
猜你喜欢
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
  • 2023-01-18
  • 2021-11-29
  • 2011-11-25
相关资源
最近更新 更多