如何在此循环中忽略使用.ignoreCase?

时间:2014-02-27 07:39:32

标签: javascript

我在stackoverflow上找到了这段代码,它用于从字符串数组中删除重复项。

arr = arr.filter (function (v, i, a) { return a.indexOf (v) == i });

我希望它在查找重复项时忽略大小写。问题是我不太了解代码所以我不知道要附加什么变量.ignoreCase。

完整代码:

HTML

<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <textarea cols="80" rows="15"  id="words" name="words">

</textarea>
<br/> 
<br/> 
<br/> 
<br/>

<button onclick="show()">Click me</button

  </body>
</html>

脚本:

<script>

function array_contains(a, obj) 
{

    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}



function show()
{
    var words = document.getElementById('words').value;
    var arr = words.split(' '); // here is the array


    ///GET RID OF DUPES ///


    arr = arr.filter (function (v, i, a) { return a.indexOf (v) == i });

    /// REMOVE USELESS WORDS ///

    alert(arr.length);

}


</script>

1 个答案:

答案 0 :(得分:0)

您已经得到了关于如何解释其他代码的答案,这些答案可能同样重要:

已将arr = arr.filterarr2 = arr1.filter()切换为仅清楚地表明返回是不同的数组。

//    filter: Create a new array by traversing the given Array
//            and adding (pushing) each element from which argument
//            function returns "true".
arr2 = arr1.filter(
    // Argument function:
    // If this function returns true. Add current element to
    // the new Array returned by "filter".
    function(v, i, a) {
        //   |  |  |
        //   |  |  +---- Array being traversed (arr1)
        //   |  +------- Index of current item
        //   +---------- Value of current item (arr1[i])
        //
        //          +--- Return _first_ index of arr1 where
        //          |    value "v" can be found.
        return a.indexOf(v) == i; 
        //     |         |     |
        //     +--------->----->---> If "i" is first index of value "v", then
        //                           return true.
        //                           In effect adding the element to the new
        //                           Array "arr2"
    }
);

与原始arr_Aarr_B结果相同:

arr_B = [];

for (i = 0; i < arr_A.length; ++i)
    if (arr_A.indexOf(arr_A[i]) === i)
        arr_B.push(arr_A[i]);