gpt4 book ai didi

javascript - 在javascript中搜索字符串中缺少的字母表中的字母

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:29 25 4
gpt4 key购买 nike

我正在编写一些代码,这些代码将搜索一个字符串并返回丢失的所有字母表中的字母。这是我的:

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 之前的所有字母添加到缺失数组中。

如有任何帮助,我们将不胜感激。

最佳答案

在您的循环中,您可以使用 indexOf() 来查看您的输入中是否存在该字母。这样的事情会起作用:

for (var i = 0; i < a.length; i++) {
if(s.indexOf(a[i]) == -1) { hits.push(a[i]); }
}

希望对您有所帮助!你可以看到它在这个 JS Fiddle 中工作:https://jsfiddle.net/573jatx1/1/

关于javascript - 在javascript中搜索字符串中缺少的字母表中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35613451/

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