DIV CSS 佈局教程網

動手打造 ES5 陣列新方法:every、map、filter、reduce 全解析
編輯:關於JavaScript     

ECMAScript 5 為陣列帶來了一批極其實用的新方法,例如 every、some、forEach、map、filter 以及 reduce。這些方法讓集合遍歷與轉換的語法變得優雅許多。本文透過一個名為 jLip 的輕量函式庫,示範如何在舊環境中自行補上這些能力,並理解它們背後的實作原理。

核心思路是抽出兩個通用函式:each 負責處理大部分需要遍歷的方法,reduce 則專門處理歸約類操作。透過一個 kind 參數來區分不同方法的行為,就能用一份迴圈邏輯覆蓋多個方法。

完整實作程式碼

/*!
* jLip JavaScript Library v0.1
* Copyright 2012, Lip2up (lip2up@qq.com)
* Just for free use, NO LICENSE
*/
(function() {
function extend(target, props) {
for (var m in props) {
if (target[m] === undefined) target[m] = props[m];
}
}
var fns = { every: 1, some: 2, forEach: 3, map: 4, filter: 5 },
reduceError = 'Reduce of empty array with no initial value';
function each(fn, _this, kind) {
var len = this.length, ret = kind == fns.filter ? []
: kind == fns.map ? Array(len) : undefined,
find = kind == fns.some, i, v;
for (i = 0; i < len; i++) {
if (this[i] !== undefined) {
v = fn.call(_this, this[i], i, this);
switch (kind) {
case fns.every:
case fns.some:
if (v === find) return find;
break;
case fns.map:
ret[i] = v;
break;
case fns.filter:
if (v === true) ret[ret.length] = this[i];
break;
}
}
}
return kind >= fns.forEach ? ret : !find;
}
function reduce(fn, init, right) {
var len = this.length, i, prev, inc = right ? -1 : 1;
if (len == 0 && init === undefined)
throw TypeError(reduceError);
for (i = right ? len - 1 : 0, prev = init;
prev === undefined && (right ? i >= 0 : i < len);
i += inc) {
prev = this[i];
}
if (prev === undefined && i == (right ? -1 : len))
throw TypeError(reduceError);
for (; (right ? i >= 0 : i < len); i += inc) {
if (this[i] !== undefined)
prev = fn(prev, this[i], i, this);
}
return prev;
}
extend(Array.prototype, {
every: function(fn, _this) {
return each.call(this, fn, _this, fns.every);
},
some: function(fn, _this) {
return each.call(this, fn, _this, fns.some);
},
forEach: function(fn, _this) {
return each.call(this, fn, _this, fns.forEach);
},
map: function(fn, _this) {
return each.call(this, fn, _this, fns.map);
},
filter: function(fn, _this) {
return each.call(this, fn, _this, fns.filter);
},
reduce: function(fn, init) {
return reduce.call(this, fn, init);
},
reduceRight: function(fn, init) {
return reduce.call(this, fn, init, true);
}
});
})();

設計要點

extend 只在目標屬性為 undefined 時才補上,避免覆蓋原生已經存在的實作。each 透過 kind 決定回傳值型別:filter 回傳新陣列、map 回傳同長度陣列、其餘則回傳布林值。而 reduce 則以 right 參數控制是否從右向左遍歷,並在空陣列且無初始值時拋出型別錯誤,與原生行為保持一致。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved