我正在为一个网站制作一段代码,该网站将在数组中包含一个名称列表,并选择一个随机名称,我想添加一个功能,让用户添加或删除数组中的名称。我拥有所有这些功能,但在删除名称时,用户必须键入名称以匹配数组中的Case。我试图这样做就是Case-Insensitive,我做错了什么?
<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>
答案 0 :(得分:43)
var array = ['I', 'hAve', 'theSe', 'ITEMs'],
query = 'these',
result = array.findIndex(item => query.toLowerCase() === item.toLowerCase());
console.log(result); // 2
&#13;
答案 1 :(得分:26)
在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
答案 2 :(得分:21)
简单的方法是拥有一个包含所有大写字母的临时数组。然后您可以比较用户输入。所以你的代码可能变成这样的东西:
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(" | ");
}
}
希望这有助于解决您的问题。
答案 3 :(得分:6)
最优雅的解决方案是首先将数组转换为字符串,然后进行不区分大小写的比较。例如:
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
}
答案 4 :(得分:5)
可能最好创建自己的自定义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'));
&#13;
甚至
'use strict';
var customIndexOf = function(array, searchElement, fromIndex) {
return array.map(function(value) {
return value.toLowerCase();
}).indexOf(searchElement.toLowerCase(), fromIndex);
};
var names = [
'John',
'Anne',
'Brian'
];
console.log(customIndexOf(names, 'aNnE'));
&#13;
您可能还想添加更多检查,以确保数组中的每个元素实际上都是String
,并且searchElement
实际上也是String
。如果是ES5之前,则加载适当的shims
答案 5 :(得分:1)
可以通过map方法使用。例如,见下面的代码
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
}
}
答案 6 :(得分:1)
found = myArray.find(key => key.toUpperCase() === searchString.toUpperCase()) != undefined;
示例:
myArray = ['An', 'aRRay', 'oF', 'StringS'];
searchString = 'array';
found = myArray.find(key => key.toUpperCase() === searchString.toUpperCase()) != undefined;
if (found ) {
// The array contains the search string
}
else {
// Search string not found
}
注意:数组不能包含undefined
作为值。
答案 7 :(得分:0)
将数组转换为由分隔符分隔的字符串,将该字符串转换为小写,然后通过相同的分隔符将字符串拆分回数组:
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:');
}
答案 8 :(得分:0)
这是最短的一个。
haystack.join(' ').toLowerCase().split(' ').indexOf(needle.toLowerCase())
答案 9 :(得分:0)
我需要与此类似的东西,我需要使用includes
比较两个字符串,并且需要能够支持不区分大小写的搜索,因此我编写了以下小函数
function compare(l1: string, l2: string, ignoreCase = true): boolean {
return (ignoreCase ? l1.toLowerCase() : l1).includes((ignoreCase ? l2.toLowerCase() : l2));
}
相同的原则可能适用于indexOf
,如下所示
function indexOf(l1: string, l2: string, ignoreCase = true): number {
return (ignoreCase ? l1.toLowerCase() : l1).indexOf((ignoreCase ? l2.toLowerCase() : l2));
}
我知道这不是专门的Array.indexOf
,但希望这对某人在旅行途中遇到此问题有所帮助。
不过,要回答ops问题,您可以将其类似地应用于与answer中与此@ULIT JAIDEE组合而成的数组(对此的微小变化是使用tilda字符作为分隔符,以防出现以下情况)数组值包含空格)
function compare(l1: any[], l2: any[], ignoreCase = true): boolean {
return (ignoreCase ? l1.join('~').toLowerCase().split('~') : l1).indexOf((ignoreCase ? l2.join('~').toLowerCase().split('~') : l2));
}
再次希望这会有所帮助。
答案 10 :(得分:0)
// unique only, removes latter occurrences
array.filter((v, i, a) => a.findIndex(j => v.toLowerCase() === j.toLowerCase()) === i);
答案 11 :(得分:-2)
你不能让它不区分大小写。我会使用一个对象来保存一组名称:
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();