javascript - 如何在这个循环中忽略 use .ignoreCase ?

标签 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>

最佳答案

您已经得到了答案,这里是其他代码的解释,这可能同样重要:

已将 arr = arr.filter 切换为 arr2 = 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_A 作为原始值和 arr_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]);

关于javascript - 如何在这个循环中忽略 use .ignoreCase ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22062066/

相关文章:

javascript - masonry 网格 : Instagram API + MacyJS - Javascript problem

javascript - 如何在nodejs中上传文件到远程服务器并更改其路径?

javascript - 使用 Gulp.js 模板编译器渲染 HTML

javascript - 使用 fetch 发出 POST 请求

php - 计算 Ubuntu 中的逻辑代码行

javascript - 如何在数组中添加一个对象?

javascript - 你能永久地添加到 Javascript 中的数组吗?

javascript - 如何在 JQuery 中将相邻兄弟选择器与 "this"一起使用?

javascript - 使用 javascript 将 html 节点替换为字符串

javascript - jQuery - 查找最后选择的元素