如何使Array.indexOf()不区分大小写?
我正在制作一个网站的代码片段,将有一个数组中的名称列表,并select一个随机的名称,我想添加一个function,将允许用户添加或删除数组中的名称。 我拥有所有这些function,但是在删除名称时,用户必须键入名称以匹配数组中的Case。 我试图这样做是不区分大小写的,我做错了什么?
<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>
简单的方法是有一个临时数组,其中包含大写的所有名称。 然后你可以比较用户的input。 所以你的代码可能会变成这样:
function delName() { var dnameVal = document.getElementById('delname').value; var upperCaseNames = names.map(function(value) { return value.toUpperCase(); }); var pos = upperCaseNames.indexOf(dnameVal.toUpperCase()); if(pos === -1) { alert("Not a valid name"); } else { names.splice(pos, 1); document.getElementById('canidates').innerHTML = "<strong>List of Canidates:</strong> " + names.join(" | "); } }
希望这有助于解决您的问题。
在ECMA-262第5版中,您可以使用Array.prototype.some
。
var array = [ 'I', 'hAve', 'theSe', 'ITEMs' ]; var query = 'these'.toLowerCase(); var index = -1; array.some(function(element, i) { if (query === element.toLowerCase()) { index = i; return true; } }); // Result: index = 2
ES2015 findIndex :
var array = ['I', 'hAve', 'theSe', 'ITEMs'], query = 'these'; array.findIndex(item => query.toLowerCase() === item.toLowerCase());
可能最好创build自己的自定义indexOf
方法,就像这样。
'use strict'; var customIndexOf = function(arrayLike, searchElement) { var object = Object(arrayLike); var length = object.length >>> 0; var fromIndex = arguments.length > 2 ? arguments[2] >> 0 : 0; if (length < 1 || typeof searchElement !== 'string' || fromIndex >= length) { return -1; } if (fromIndex < 0) { fromIndex = Math.max(length - Math.abs(fromIndex), 0); } var search = searchElement.toLowerCase(); for (var index = fromIndex; index < length; index += 1) { if (index in object) { var item = object[index]; if (typeof item === 'string' && search === item.toLowerCase()) { return index; } } } return -1; }; var names = [ 'John', 'Anne', 'Brian' ]; console.log(customIndexOf(names, 'aNnE'));
最优雅的解决scheme将首先将数组转换为string,然后做一个不区分大小写的比较。 例如:
var needle = "PearS" var haystack = ["Apple", "banNnas", "pEArs"]; var stricmp = haystack.toString().toLowerCase(); // returns // "apple,bananas,pears" if (stricmp.indexOf(needle.toLowerCase()) > -1) { // the search term was found in the array } else { // the search term was not found in the array }
用地图法可以使用。 例如见下面的代码
var _name = ['prasho','abraham','sam','anna'] var _list = [{name:'prasho'},{name:'Gorge'}]; for(var i=0;i<_list.length;i++) { if(_name.map(function (c) { return c.toLowerCase(); }).indexOf(_list[i].name.toLowerCase()) != -1) { //do what ever }else{ //do what ever } }
更多信息
将数组转换为由分隔符分隔的string,将该string转换为小写字母,然后使用相同的分隔符将string拆分回数组:
function findIt(arr, find, del) { if (!del) { del = '_//_'; } arr = arr.join(del).toLowerCase().split(del); return arr.indexOf(find.toLowerCase()); } var arr = ['Tom Riddle', 'Ron Weasley', 'Harry Potter', 'Hermione Granger']; var find = 'HaRrY PoTtEr'; var index = findIt(arr, find); if (~index) { alert('Found ' + arr[index] + '! :D'); } else { alert('Did not find it. D:'); }
你不能让它不区分大小写。 我会用一个对象来保存一组名称:
function Names() { this.names = {}; this.getKey = function(name) { return name.toLowerCase(); } this.add = function(name) { this.names[this.getKey(name)] = name; } this.remove = function(name) { var key = this.getKey(name); if (key in this.names) { delete this.names[key]; } else { throw Error('Name does not exist'); } } this.toString = function() { var names = []; for (var key in this.names) { names.push(this.names[key]); } return names.join(' | '); } } var names = new Names(); function update() { document.getElementById('canidates').innerHTML = '<strong>List of Canidates:</strong> ' + names; } function deleteName() { var name = document.getElementById('delname').value; try { names.remove(name); update(); } catch { alert('Not a valid name'); } } update();