js Array扩展方法


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /www/wwwroot/fawdlstty.com/wp-content/plugins/wp-syntax/wp-syntax.php on line 383

js的Array对象的处理能力比较强大,下面几个函数是给它再新增几个扩展方法使其更方便使用
部分方法在最新版Webkit已经实现,但由于IE8等低端浏览器还占有大批用户,所以还得实现一遍,另外splice不是很方便使用,个人感觉用insert、remove方法更直观

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//数组处理程序
if (!Array.prototype.forEach) {
	Array.prototype.forEach = function (callback, thisArg) {
		var T, k;
		if (this == null) {
			throw new TypeError(" this is null or not defined");
		}
		var O = Object(this);
		var len = O.length >>> 0; // Hack to convert O.length to a UInt32  
		if ({}.toString.call(callback) != "[object Function]") {
			throw new TypeError(callback + " is not a function");
		}
		if (thisArg) {
			T = thisArg;
		}
		k = 0;
		while (k < len) {
			var kValue;
			if (k in O) {
				kValue = O[k];
				callback.call(T, kValue, k, O);
			}
			k++;
		}
	};
}
 
//查询数组中是否存在元素
if (!Array.prototype.in_array) {
	Array.prototype.in_array = function (e) {
		for (i = 0; i < this.length; i++) {
			if (this[i] == e)
				return true;
		}
		return false;
	}
}
 
//插入元素
if (!Array.prototype.insert) {
	Array.prototype.insert = function (index, elem) {
		return this.splice(index, 0, elem);
	}
}
 
//删除元素
if (!Array.prototype.remove) {
	Array.prototype.remove = function (index) {
		return this.splice(index, 1);
	}
}