我正在尝试将输入的文本与预定义数组中的单词列表相匹配。但是,它没有返回任何内容,甚至 console.log 也没有返回任何内容。我无法弄清楚为什么 out 循环没有启动。任何帮助将不胜感激。
var actions = ["north", "south", "east", "west", "up", "down", "get", "take", "pick up", "use", "drop", "open", "close"];
var inputTextBox = document.getElementById("inputTextBox");
inputTextBox.addEventListener("keypress", function(event) {
var stringArray = [];
var x = event.which || event.keyCode;
var inString = inputTextBox.value.toLowerCase();
if (x === 13) {
stringArray = inString.split(" ");
console.log("stringArray is --- " + stringArray + " --- length is " + stringArray.length);
for (var i = 0; i < stringArray; i++) {
console.log("outer loop is " + stringArray[i]);
for (var j = 0; j < actions.length; j++) {
if (stringArray[i] === actions[j]) {
console.log(stringArray[i]);
}
}
}
}
}
<input id="inputTextBox" type="text" maxlength="200" placeholder="words here" autofocus></input>
最佳答案
您忘记使用 length
属性,因为 stringArray
是一个数组,您必须使用它的 length
来迭代它。
for (var i = 0; i < stringArray.length; i++) {
................................^^^^
"However, it's not returning anything, even the console.log doesn't return anything."
要查看更改,您必须按 enter
。
var x = event.which || event.keyCode;
event.which
属性指示按下的特定键或按钮,13
是 enter
命令的键。
var actions = ["north", "south", "east", "west", "up", "down", "get", "take", "pick up", "use", "drop", "open", "close"];
var inputTextBox = document.getElementById("inputTextBox");
inputTextBox.addEventListener("keypress", function(event) {
var stringArray = [];
var x = event.which || event.keyCode;
var inString = inputTextBox.value.toLowerCase();
if (x === 13) {
stringArray = inString.split(" ");
console.log("stringArray is --- " + stringArray + " --- length is " + stringArray.length);
for (var i = 0; i < stringArray.length; i++) {
console.log("outer loop is " + stringArray[i]);
for (var j = 0; j < actions.length; j++) {
if (stringArray[i] === actions[j]) {
console.log(stringArray[i]);
}
}
}
}
});
<input id="inputTextBox" type="text" maxlength="200" placeholder="words here" autofocus></input>
关于javascript - 我的嵌套循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691972/