javascript - 我的嵌套循环不起作用

标签 javascript arrays for-loop nested-loops

我正在尝试将输入的文本与预定义数组中的单词列表相匹配。但是,它没有返回任何内容,甚至 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 属性指示按下的特定键或按钮,13enter 命令的键。

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/

相关文章:

c - 学习 C 试图通过函数找出这个 malloc 的东西

javascript - 计算页面上损坏的链接数

javascript - 使用 PHP 从我的游戏目录中随机提取 8 个图像

c# - 将 UTC 时间注入(inject)页面

Javascript 相等怪异

javascript - 使用语法电子邮件检查器实现实时电子邮件检查器

javascript - 将键值对(数组中的值)添加到数组中的特定对象

python - 在 Python 中将整数列表转换为字节数组

bash - 如何检查 bash for 循环中的不平等?

java - 计数器未按预期指示二维数组