我的任务是有一个接受用户输入的文本框,将输入压入数组,然后根据复选框的状态检查硬编码数组,以评估用户输入元素是否与硬编码数组匹配元素。何时/何时/为什么第一个数组元素下降?
在基本情况下,字符串必须完全匹配(基于区分大小写),我的代码与匹配的单词一致,并忽略不匹配的单词。我将匹配的单词添加到一个字符串中,然后在警报中显示该字符串。但是,在第二种情况下,字符串打算忽略区分大小写(因此用户可以输入大小写的任意组合),我的警报显示匹配的名称列表总是会丢失输入的第一个字在用户输入文本框中。区分大小写逻辑看起来工作正常 - 问题是其中一个单词被丢弃。
这里是我的代码首先为HTML外壳
function process() {
//create string to store user input
var s = document.getElementById("inputTextBox").value;
//testing text area to display captured input
document.getElementById("textArea").value = s;
//create array to store user input
var inputArray = [];
//create array of names to check user input against
var namesArray = ["John", "Bill", "Mary", "Ted", "Roger"];
//split the string by spaces
var input = s.split(" ");
//put the split string into the inputArray
inputArray = s.split(" ");
//determine length of arrays
var inputArrayLength = inputArray.length;
var nameArrayLength = namesArray.length;
//create string to hold matched names
var matchedNames = "";
for(var i = 0; i < inputArrayLength; i++)
{
//set current name string to current array element
currName = inputArray[i];
//first determine if the checkbox IS checked
if ((document.getElementById("checkBox").checked) == true)
{
//if it is checked, determine if currName == name in namesArray
if (currName == 'John' || currName == 'Bill' || currName == 'Mary' || currName == 'Ted' || currName == 'Roger')
{
matchedNames = matchedNames.concat(currName + " ");
}}
//if it is NOT checked
else if ((document.getElementById("checkBox").checked) == false)
{
//traverse array and toLowerCase all elements
for (var j = 0; j < inputArrayLength; j++)
{
inputArray[j] = inputArray[j].toLowerCase();
}
//then determine if toLowerCase string is present in array
if (currName == 'john' || currName == 'bill' || currName == 'mary' || currName == 'ted' || currName == 'roger')
{
matchedNames = matchedNames.concat(currName + " ");
}
}
}
document.getElementById("textArea").value = matchedNames;
//alert matched names
alert("Matched Names: " + matchedNames + ".");
}
<label>Please enter a series of first names, separated by spaces</label>
<br />
<input id="inputTextBox" type="text" name="textBox1" style="width: 200px;"/>
<br />
<label><input id="checkBox" type="checkbox" name="checkbox1" />toggle case sensitivity</label>
<br />
<input id="Button1" type="button" value="Process" onclick="process();"/>
<br />
<textarea id="textArea" name="textArea1" rows="2" cols="1" style="width: 400px;"></textarea>
我知道有许多文体问题(蹩脚的名字),一些严重的冗余,而这很可能收紧逻辑上使用更少的线等
谢谢你的时间和精力!对此,我真的非常感激。 – grcHIDDEN