gpt4 book ai didi

javascript - 如何使 Array.indexOf() 不区分大小写?

转载 作者:IT王子 更新时间:2023-10-29 02:52:55 26 4
gpt4 key购买 nike

我正在为一个网站编写一段代码,该网站将在一个数组中包含一个名称列表并随机选择一个名称,我想添加一个功能,让用户可以从数组中添加或删除一个名称。我拥有所有这些功能,但是在删除名称时,用户必须键入名称以匹配数组中的大小写。我试图使它不区分大小写,我做错了什么?

<html>
<!--Other code uneeded for this question-->
<p id="canidates"></p>
<body>
<input type="text" id="delname" /><button onclick="delName()">Remove Name from List</button>
<script>

//Array of names

var names = [];

//Other code uneeded for this question

//List of Canidates
document.getElementById('canidates').innerHTML =
"<strong>List of Canidates:</strong> " + names.join(" | ");

//Other code uneeded for this question

//Remove name from Array

function delName() {
var dnameVal = document.getElementById('delname').value;
var pos = names.indexOf(dnameVal);
var namepos = names[pos]
var posstr = namepos.toUpperCase();
var dup = dnameVal.toUpperCase();
if(dup != posstr) {
alert("Not a valid name");
}
else {
names.splice(pos, 1);
document.getElementById('canidates').innerHTML =
"<strong>List of Canidates:</strong> " + names.join(" | ");
}
}
</script>
</body>
</html>

最佳答案

ES2015 findIndex :

var array = ['I', 'hAve', 'theSe', 'ITEMs'],
indexOf = (arr, q) => arr.findIndex(item => q.toLowerCase() === item.toLowerCase());

console.log( indexOf(array, 'i') ) // 0
console.log( indexOf(array, 'these') ) // 2
console.log( indexOf(array, 'items') ) // 3

关于javascript - 如何使 Array.indexOf() 不区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718349/

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