我的任務是有一個接受用戶輸入的文本框,將輸入壓入數組,然後根據複選框的狀態檢查硬編碼數組,以評估用戶輸入元素是否與硬編碼數組匹配元素。何時/何時/爲什麼第一個數組元素下降?
在基本情況下,字符串必須完全匹配(基於區分大小寫),我的代碼與匹配的單詞一致,並忽略不匹配的單詞。我將匹配的單詞添加到一個字符串中,然後在警報中顯示該字符串。但是,在第二種情況下,字符串打算忽略區分大小寫(因此用戶可以輸入大小寫的任意組合),我的警報顯示匹配的名稱列表總是會丟失輸入的第一個字在用戶輸入文本框中。區分大小寫邏輯看起來工作正常 - 問題是其中一個單詞被丟棄。
這裏是我的代碼首先爲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