【发布时间】: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