JavaScript去除数组中的重复值

时间:2023-03-09 13:35:12
JavaScript去除数组中的重复值

用原型函数(prototype)可以定义一些很方便的自定义函数,实现各种自定义功能。

Javascript 中的原型函数(prototype)的工作原理,在 javascript 中每次声明新函数的过程中,就会为其创建一个 prototype 的属性。在未加其他附带条件情况下,所有的 prototype 属性都会自动获取 constractor 属性,constructor 内包含一个指向 prototype 属性所属函数的指针(就是说 constructor 回指构造函数本身)。

举个例子来说,Fruit.prototype.constructor 指向 Fruit。并且可以通过这个构造函数,为其添加更多的属性和方法。

当调用构造函数创建一个新实例后,该实例内部包含一个指针指向构造函数的原型函数。此时我们不用去关心内部的这个指针到底是什么(这个指针还的确有个名字:__proto__ 估计是为了对应 prototype 而起的名字吧 ~\(≧▽≦)/~ ),只需记住它的指向即可(指向构造函数的原型函数)。需要注意的是,这个 __proto__ 只存在于函数实例与构造函数的原型函数之间,而非实例与构造函数之间。

下面是使用 prototype 自定义了3个函数,分别是去掉数组中的重复值,还有求数组中的最大值与最小值。

数组定义为: var arr = [2,1,3,2,1,4,3,4,2,1];

程序代码为:

<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 = [2,1,3,2,1,4,3,4,2,1]; var btn1 = document.getElementById("btn1");
btn1.onclick = function(){
arr.unique();
alert(arr.toString());
} var btn2 = document.getElementById("btn2");
btn2.onclick = function(){
alert(arr.max());
} var btn3 = document.getElementById("btn3");
btn3.onclick = function(){
alert(arr.min());
}
</script>