我删除重复项的功能不起作用,有什么建议吗?

0 javascript

<p id="demo"></p>

<script>

//This is the email list

var emailList =["adam@yahoo.edu\n", "henry@yahoo.edu\n", "john@yahoo.edu\n", "sally@yahoo.edu\n", "adam@yahoo.edu\n", "david@yahoo.edu\n", "myhome@yahoo.edu\n", "david@yahoo.edu\n", "david@yahoo.edu\n", "hunger@yahoo.edu\n", "madison@yahoo.edu\n", ];

//I am removing @yahoo.edu

function removeAddress(list){
    for (var i = 0; i < list.length; i++) {
        list[i] = list[i].replace("@yahoo.edu", " ");
    }
}

//Function to remove the duplicates in the list

function removeDuplicates(list)
{
    var hash = {};
    for (var i = 0; i < list.length; i++)
    {
        var array = list[i];
        for (var j = 0; j < array.length; j++) 
        {
            var val = array[j];
            var hashedVal = hash[val];
            if (hashedVal === undefined) 
            {
                hash[val] = true;
            }
            else 
            {
                array.splice(j, 1);
                if (array.length == 0)
                {
                    list.splice(i, 1);
                }
            }
        }
    }
}
document.getElementById("demo").innerHTML = emailList;
//Remove @yahoo.edu from the list

removeAddress(emailList);

//Sort the list

emailList.sort();

//Remove the duplicates

removeDuplicates(emailList);

//Print the list

document.getElementById("demo").innerHTML = emailList;
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 5

首先,我不确定你为什么要遍历带有2个循环的1维数组.这不是必要的.其次,你在遍历数组的同时也删除了元素.删除元素后,将其后面的所有元素向前推送1个索引.然后i递增,导致您错过一个项目.如果要继续for循环和使用.splice(),则需要i在删除项目时手动递减.此外,您只需要一个循环,因为它emailList是一个字符串数组.

function removeDuplicates(list)
{
  var hash = {};
  var newList = [];
  for (var i = 0; i < list.length; i++)
  {
    var email = list[i];
    if (hash[email] === undefined) {
      hash[email] = true;
    } else {
      list.splice(i, 1);
      i --;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

http://codepen.io/anon/pen/YyKJOP