我正在处理一些代码,它将搜索字符串并返回字母表中缺少的任何字母.这是我有的:
- 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”);
结果将所有字母添加到缺少的数组之前.
任何帮助将不胜感激.
解决方法
在你的循环中,你可以使用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/