我正在研究一些代码,这些代码将搜索字符串并返回缺少的字母表中的任何字母。这就是我所拥有的:
function findWhatsMissing(s){
var a = "abcdefghijklmnopqrstuvwxyz";
//remove special characters
s.replace(/[^a-zA-Z]/g, "");
s = s.toLowerCase();
//array to hold search results
var hits = [];
//loop through each letter in string
for (var i = 0; i < a.length; i++) {
var j = 0;
//if no matches are found, push to array
if (a[i] !== s[j]) {
hits.push(a[i]);
}
else {
j++;
}
}
//log array to console
console.log(hits);
}
但是使用测试用例: findWhatsMissing(“d a b c”);
将d添加到缺失数组之前的所有字母中的结果。
非常感谢任何帮助。
答案 0 :(得分:7)
在循环中,您可以使用indexOf()
查看输入中是否存在该字母。像这样的东西会起作用:
for (var i = 0; i < a.length; i++) {
if(s.indexOf(a[i]) == -1) { hits.push(a[i]); }
}
希望有所帮助!你可以看到它在这个JS小提琴中工作:https://jsfiddle.net/573jatx1/1/
答案 1 :(得分:2)
Adam Konieska说。这样的事情会起作用:
function findWhatsMissing(s) {
var a = "abcdefghijklmnopqrstuvwxyz";
s = s.toLowerCase();
var hits = [];
for (var i = 0; i < a.length; i++) {
if(s.indexOf(a[i]) == -1) { hits.push(a[i]); }
}
console.log(hits);
}
findWhatsMissing("d a b c");
答案 2 :(得分:2)
可以使用Array.prototype.filter()
并在每个循环中使用indexOf()
function findWhatsMissing(s){
var a = "abcdefghijklmnopqrstuvwxyz";
//remove special characters
s = s.replace(/[^a-zA-Z]/g, "");
s = s.toLowerCase();
return a.split('').filter(function(letter){
return s.indexOf(letter) === -1;
});
}
alert( findWhatsMissing('d f v'))
答案 3 :(得分:2)
您可以使用indexOf:
function findWhatsMissing(s){
var a = "abcdefghijklmnopqrstuvwxyz";
//remove special characters
s = s.replace(/[^a-zA-Z]/g, "");
s = s.toLowerCase();
//array to hold search results
var hits = [];
//loop through each letter in string
for (var i = 0; i < a.length; i++) {
//if no matches are found, push to array
if (s.indexOf(a[i]) == -1) {
hits.push(a[i]);
}
}
//log array to console
return hits;
}
alert(JSON.stringify(findWhatsMissing(' d a b c ')));
或两个for循环:
function findWhatsMissing(s){
var a = "abcdefghijklmnopqrstuvwxyz";
//remove special characters
s = s.replace(/[^a-zA-Z]/g, "");
s = s.toLowerCase();
//array to hold search results
var hits = [];
//loop through each letter in string
for (var i = 0; i < a.length; i++) {
//if no matches are found, push to array
var found = false;
for (var j = 0; j < s.length; j++) {
if (s[j] == a[i]) {
found = true;
break;
}
}
if (!found) {
hits.push(a[i]);
}
}
//log array to console
return hits;
}
alert(JSON.stringify(findWhatsMissing(' d a b c ')));