我在一次小挑战中遇到了一些麻烦。我试图检查是否在数组中找到字符串的字符,如果是,请停止循环,记录该值,然后重新开始使用新的字符串字符。谁能elp
function LetterChanges(str) {
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
// code goes here
var myString = "";
for(var i = 0; i <= myString.length; i++) {
for(var o = 0; o < 25; o++){
var getChar = myString += str.charAt(i)
if (getChar == alphabet[o]){
alert(getChar);
break;
}
}
}
alert(getChar);
}
// keep this function call here
LetterChanges("Test");`
答案 0 :(得分:1)
function LetterChanges(str) {
// code goes here
var regex=/[abcdefghijklmnopqrstuvwxyz]/;
// simply you can give as below
regex = /[a-z]/;
//if you want to match Cap A-Z too make the regex to ignore case as below
// regex = /[a-z]/i;
var myString = "";
for (var i = 0; i < str.length; i++) {
var char = str[i];
if (regex.test(char)) {
myString += char;
console.log(myString)
}
}
console.log(myString);
}
// keep this function call here
LetterChanges("Test");
答案 1 :(得分:0)
debugger
和断点。他们会帮助您弄清楚您的代码在做什么。alphabet.length
而不是25
var getChar
似乎没必要。试着做if(str.chartAt(i) == alphabet[o])
答案 2 :(得分:0)
function LetterChanges(str) {
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
for(var i = 0; i <= str.length; i++) {
for(var o = 0; o < 25; o++){
if (str.charAt(i) == alphabet[o]){
alert(getChar);
break;
}
}
}
alert(getChar);
}
// keep this function call here
LetterChanges("Test"); </script>
请注意,字母'T'在数组中不匹配。所以只有'e','s','t'会警惕。