如何在javascript的set
中执行不区分大小写的查找?
我遇到的情况是我有一组允许的字符串,但不能确保它们将处于哪种情况。我需要针对该组验证用户输入。我该如何实现?
const countries = new Set();
countries.add("USA");
countries.add("japan");
// returns false, but is there any way I could get
//`my set to ignore case and return true?`
console.log(countries.has("usa"));
console.log(countries.has("USA"));
答案 0 :(得分:4)
在添加字符串之前或执行.toLowerCase
检查之前,始终始终对字符串调用.has
。当然,您也可以将其抽象为类(如果确实有必要):
class CaseInsensitiveSet extends Set {
constructor(values) {
super(Array.from(values, it => it.toLowerCase()));
}
add(str) {
return super.add(str.toLowerCase());
}
has(str) {
return super.has(str.toLowerCase());
}
delete(str) {
return super.delete(str.toLowerCase());
}
}
const countries = new CaseInsensitiveSet([
"Usa",
]);
console.log(countries.has("usa")); // true
答案 1 :(得分:0)
简短的回答是“否”。 has
使用SameValueZero算法来寻找值的存在。参见比较表here。
如果不考虑性能,则可以尝试进行两次搜索,一次搜索为大写字母,一次搜索为小写字母,然后确定该值是否实际存在。
更好的方法是始终通过将值转换为大写/小写来插入值,并相应地匹配它们的存在。
答案 2 :(得分:0)
设置检查您提供的确切数据。最简单的解决方案是将数据保存为小写或大写,然后使用.toLoserCase()
String
方法在集合中进行搜索。
示例:
// Save data in lowecase
const set1 = new Set(['test', 'other']);
console.log(set1.has('Test'));
// expected output: false
console.log(set1.has('Other'.toLowerCase()));
// expected output: false
答案 3 :(得分:0)
您可以在hasIgnoreCase()
上添加Set
原型。
Set.prototype.hasIgnoreCase = function(str) {
return this.has(str) || this.has(str.toUpperCase());
}
const countries = new Set();
countries.add("USA");
countries.add("japan");
// returns false, but is there any way I could get
//`my set to ignore case and return true?`
console.log(countries.hasIgnoreCase("usa"));
console.log(countries.hasIgnoreCase("USA"));