日期:2014-05-16  浏览次数:20372 次

数组中去除重复元素 求解释这段代码或更好方法
[code=JScript][/code]Array.prototype.distinct=function(){
  var a=[],b=[];
  for(var prop in this){
  var d = this[prop];
  if (d===a[prop]) continue; //防止循环到prototype
  if (b[d]!=1){
  a.push(d);
  b[d]=1;
  }
  }
  return a;
}

这是在一个帖子里看到的一段代码 去除数组中重复元素 额 看不大懂 var prop in this 这是定义为下标吗? 第一个if判断语句又是什么意思 有点晕 寻高手为菜鸟解答 若有更好的方法更请赐教(最好带说明 体谅一下新手 拜谢)

------解决方案--------------------
http://topic.csdn.net/u/20100604/09/eb9f87ca-7d8f-44b4-b4f0-9815dcc05dfc.html
------解决方案--------------------
http://topic.csdn.net/u/20111229/22/f6aa6dba-ed0d-4642-8e9d-a6557c701405.html
------解决方案--------------------
for(var prop in this){//循环遍历this,this中相应对象的key赋给prop变量。
if (d===a[prop]) continue;//去重
------解决方案--------------------
HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        Array.prototype.Contains = function (obj) {
            if (this == null || this.length <= 0) {
                return false;
            }
            var count = 0;
            for (var i = 0; i < this.length; i++) {
                if (this[i] == obj) {
                    count++;
                }
            }
            return count > 0;
        }
        Array.prototype.Distinct = function () {
            if (this.length == 0) {
                return this;
            }
            var array = [];
            for (var i = 0; i < this.length; i++) {
                if (array.Contains(this[i]) == false) {
                    array.push(this[i]);
                }
            }
            return array;
        }

        var a = new Array("0", "1", "0", "0", "2");
        alert(a.join());
        alert(a.Distinct().join());
    </script>
</head>
<body>
</body>
</html>

------解决方案--------------------
楼上代码调整格式的时候错了一行,修正如下:
JScript code

            Array.prototype.distinct = function () {
                var a = [], b = [];
                for (var i = 0; i < this.length; i++) {
                    if (b[this[i]] != 1) {
                        a.push(this[i]);
                        b[this[i]] = 1;
                    }
                }
                return a;
            }