JavaScript 5 发布有一段时间了,Array 对象新增了很多方法。但在老版本的浏览器上还不能使用,得益于 JavaScript 的动态可扩展性,我实现了这些方法,在此晒出来与君共勉。
1 /*!
2 * jLip JavaScript Library v0.1
3 *
4 * Copyright 2012, Lip2up (lip2up@qq.com)
5 * Just for free use, NO LICENSE
6 */
7
8 (function() {
9
10 function extend(target, props) {
11 for (var m in props) {
12 if (target[m] === undefined) target[m] = props[m];
13 }
14 }
15
16 var fns = { every: 1, some: 2, forEach: 3, map: 4, filter: 5 },
17 reduceError = 'Reduce of empty array with no initial value';
18
19 function each(fn, _this, kind) {
20 var len = this.length, ret = kind == fns.filter ? []
21 : kind == fns.map ? Array(len) : undefined,
22 find = kind == fns.some, i, v;
23
24 for (i = 0; i < len; i++) {
25 if (this[i] !== undefined) {
26 v = fn.call(_this, this[i], i, this);
27 switch (kind) {
28 case fns.every:
29 case fns.some:
30 if (v === find) return find;
31 break;
32 case fns.map:
33 ret[i] = v;
34 break;
35 case fns.filter:
36 if (v === true) ret[ret.length] = this[i];
37 break;
38 }
39 }
40 }
41
42 return kind >= fns.forEach ? ret : !find;
43 }
44
45 function reduce(fn, init, right) {
46 var len = this.length, i, prev, inc = right ? -1 : 1;
47
48 if (len == 0 && init === undefined)
49 throw TypeError(reduceError);
50
51 for (i = right ? len - 1 : 0, prev = init;
52 prev === undefined && (right ? i >= 0 : i < len);
53 i += inc) {
54 prev = this[i];
55 }
56 if (prev === undefined && i == (right ? -1 : len))
57 throw TypeError(reduceError);
58
59 for (; (right ? i >= 0 : i < len); i += inc) {
60 if (this[i] !== undefined)
61 prev = fn(prev, this[i], i, this);
62 }
63
64 return prev;
65 }
66
67 extend(Array.prototype, {
68 every: function(fn, _this) {
69 return each.call(this, fn, _this, fns.every);
70 },
71 some: function(fn, _this) {
72 return each.call(this, fn, _this, fns.some);
73 },
74 forEach: function(fn, _this) {
75 return each.call(this, fn, _this, fns.forEach);
76 },
77 map: function(fn, _this) {
78 return each.call(this, fn, _this, fns.map);
79 },
80 filter: function(fn, _this) {
81 return each.call(this, fn, _this, fns.filter);
82 },
83 reduce: function(fn, init) {
84 return reduce.call(this, fn, init);
85 },
86 reduceRight: function(fn, init) {
87 return reduce.call(this, fn, init, true);
88 }
89 });
90
91 })();
[原创] JavaScript 5 新增 Array 方法实现
TAG:JavaScript ECMAScript5 map forEach every some redu