`
eric_hwp
  • 浏览: 120191 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

通过原型实现javascript Array的去重、最大值和最小值

 
阅读更多

用原型函数(prototype)可以定义一些很方便的自定义函数,实现各种自定义功能。本次主要是实现了Array的去重、获取最大值和最小值。

实现代码如下:

<script type="text/javascript">
	Array.prototype.unique = function() {
		var a = {};
		var len = this.length;
		for (var i = 0; i < len; i++) {
			if (typeof a[this[i]] == "undefined") {
				a[this[i]] = 1;
			}
		}
			
		this.length = 0;
		for (var i in a) {
			this[this.length] = i;
		}
			
		return this;
	}
		
	Array.prototype.max = function() {
		return Math.max.apply({}, this);
	}
		
	Array.prototype.min = function() {
		return Math.min.apply({}, this);
	}
	
	
	var arr = [7,3,9,7,6,2,4,2,8];
    	console.log(arr.unique());
    	console.log(arr.max());
    	console.log(arr.min());
</script>

 这个例子写太好了

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics