Dean Edwards 写的强大的forEach

http://dean.edwards.name/

主要代码:

 1 // array-like enumeration
2 if (!Array.forEach) { // mozilla already supports this
3 Array.forEach = function(array, block, context) {
4 for (var i = 0; i < array.length; i++) {
5 block.call(context, array[i], i, array);
6 }
7 };
8 }
9
10 // generic enumeration
11 Function.prototype.forEach = function(object, block, context) {
12 for (var key in object) {
13 if (typeof this.prototype[key] == "undefined") {
14 block.call(context, object[key], key, object);
15 }
16 }
17 };
18
19 // character enumeration
20 String.forEach = function(string, block, context) {
21 Array.forEach(string.split(""), function(chr, index) {
22 block.call(context, chr, index, string);
23 });
24 };
25
26 // globally resolve forEach enumeration
27 var forEach = function(object, block, context) {
28 if (object) {
29 var resolve = Object; // default
30 if (object instanceof Function) {
31 // functions have a "length" property
32 resolve = Function;
33 } else if (object.forEach instanceof Function) {
34 // the object implements a custom forEach method so use that
35 object.forEach(block, context);
36 return;
37 } else if (typeof object == "string") {
38 // the object is a string
39 resolve = String;
40 } else if (typeof object.length == "number") {
41 // the object is array-like
42 resolve = Array;
43 }
44 resolve.forEach(object, block, context);
45 }
46 };

下面是测试代码:

 1 function print(value, key, object, tag) {
2
3 if (!tag) tag = "PRE";
4
5 document.write("<" + tag + ">" + key + ": " + value + "</" + tag + ">");
6
7 };
8
9
10
11 print('"abc"', "forEach", null, "h3");
12
13 forEach ("abc", print);
14
15
16
17 print("[1, 2, 3]", "forEach", null, "h3");
18
19 forEach ([1, 2, 3], print);
20
21
22
23 print("{a:1, b:2, c:3}", "forEach", null, "h3");
24
25 forEach ({a:1, b:2, c:3}, print);
26
27
28
29 print("arguments(1, 2, 3)", "forEach", null, "h3");
30
31 function test() {
32
33 forEach (arguments, print);
34
35 };
36
37 test(1, 2, 3);
38
39
40
41 print("fred", "forEach", null, "h3");
42
43 function Person(name, age) {
44
45 this.name = name || "";
46
47 this.age = age || 0;
48
49 };
50
51 Person.prototype = new Person;
52
53 Person.LATIN = "Homo Sapiens";
54
55 var fred = new Person("Fred", 38);
56
57 fred.language = "English";
58
59 fred.wife = "Wilma";
60
61 forEach (fred, print);
62
63
64
65 print("fred", "Person.forEach", null, "h3");
66
67 Person.forEach (fred, print);
68
69
70
71 print("Person", "forEach", null, "h3");
72
73 forEach (Person, print);




posted @ 2011-12-02 11:19 learn_javascript 阅读(...) 评论(...) 编辑 收藏