[英]Javascript create a function that returns a boolean value based on certain parameters
Thanks for taking the time to look at my problem. 感谢您抽出宝贵的时间来研究我的问题。 What I'm trying to do is create a javascript function that tests whether a sting is a particular length and also whether each element of that string can be found in another string.
我想做的是创建一个JavaScript函数,该函数测试字符串是否为特定长度,以及是否可以在另一个字符串中找到该字符串的每个元素。 The function then needs to return a boolean value of either true or false depending on whether the string is valid.
然后,该函数需要返回true或false的布尔值,具体取决于字符串是否有效。
Here's what I have: 这是我所拥有的:
N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);
function isValidGuess(inStr)
{ var valid;
var Str = inStr;
for (i=0; i<Str.length; i++)
{ if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES.length)
{ valid = true;
}
else
{ valid = false;
}
}
return valid;
}
This code is not working at all. 此代码根本不起作用。 It only returns false every time.
每次仅返回false。 Any help you could provide would be greatly appreciated.
您能提供的任何帮助将不胜感激。 Thank you.
谢谢。
N_CHOICES.length return undefined, because variable N_CHOICES is number. N_CHOICES.length返回未定义,因为变量N_CHOICES是数字。 you have to change your condition to
您必须将条件更改为
if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.