提问人:olliejjc16 提问时间:8/5/2020 更新时间:8/6/2020 访问量:340
解决在 IE8 上运行 javascript reduce() 方法的兼容性问题
Solving compatibility issues running javascript reduce() method on IE8
问:
嗨,我有一个需要在 IE8 中运行的 Web 程序。在 IE8 上,不直接支持 javascript reduce 方法,因此我为 reduce 方法转移了 Polyfill,如下所示: IE/JS:在对象上减少
现在我遇到了 Object.defineProperty() 的另一个问题,其中对象不支持此操作。我一直在寻找这个解决方案,IE8 的 Object.defineProperty 替代品,但我无法弄清楚如何将其转移到 Polyfill 作为 Object.defineProperty() 的替代品。
寻找有关如何修复 Polyfill 以使 reduce 工作并解决 Object.defineProperty() 问题或任何其他方法以在 IE8 上运行 reduce 的方法。
答:
0赞
Yu Zhou
8/6/2020
#1
reduce()
在旧浏览器中不受支持,您可以使用如下所示的 polyfill。有了这个 polyfill,可以在 IE 8 中很好地工作:reduce()
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, opt_initialValue){
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError(
'Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index = 0, length = this.length >>> 0, value, isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for ( ; length > index; ++index) {
if (!this.hasOwnProperty(index)) continue;
if (isValueSet) {
value = callback(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
示例代码:
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, opt_initialValue) {
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError(
'Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index = 0,
length = this.length >>> 0,
value, isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (; length > index; ++index) {
if (!this.hasOwnProperty(index)) continue;
if (isValueSet) {
value = callback(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
var array1 = [1, 2, 3, 4];
var reducer = function reducer(accumulator, currentValue) {
return accumulator + currentValue;
}; // 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
评论