目前浏览器似乎还没有优化Array.forEach 功能。不费吹灰之力,您就可以编写一个简单的 polyfill,它至少以 10 比 1 比执行 Array.forEach 方法。
所以你可以创建自己的Array.revEach 并让它优于原生Array.forEach,我想我希望浏览器能尽快解决Array.forEach 的性能非常慢的问题,并且不需要polyfill 实际现有的方法。
对于Array.revEach,在“Chrome 46.0.2490.22 beta-m”上,Array.forEach 的运行速度提高了 17 倍
if (Array.prototype.revEach === undefined) {
Object.defineProperty(Array.prototype, 'revEach', {
writable : false,
enumerable : false,
configurable : false,
value : function (func) {
var i;
var len = this.length-1;
for (i = len; i >= 0; i--) {
func(this[i], i, this);
}
}
});
}
只是添加实际的官方polyfill修改为reverse。评论显示我的更改。
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
// Modified by Blindman67 to revEach
if (!Array.prototype.revEach) { // name changed
Array.prototype.revEach = function(callback, thisArg) { // name changed
var T; // k defined where len was
if (this == null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(this);
var k = (O.length >>> 0)-1; // set k (counter) ToUint32
// len var removed
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
while (k >= 0) { // reverse condition
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k--; // dec counter
}
};
}