gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:29:12 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com