为什么我的for循环返回的数字大于条件中指定的数字

时间:2019-03-19 10:32:26

标签: javascript arrays function variables console.log

我创建了3个输入字段,其ID为input1input2input3,然后使用包含两个参数的函数为其分配了一个onkeypress事件(将数组作为参数传递)。第一个参数中数组的长度等于第二个参数中数组的长度。因此,两个数组都可以使用相同的索引进行访问。该函数包含一个for loop,该onkeypress事件将undefined事件分配给输入字段,然后在for循环中使用相同的索引来访问下一个数组的值。

在控制台上,它返回了<input type='text' id='input1' value='0'> <input type='text' id='input2' value='20'> <input type='text' id='input3' value='143'> <div class='input_display' > </div> ,并且索引似乎超过了for循环中的指定数字,这实际上违反了条件。现在我想知道到底是什么问题?

html:

function updown(array, array_2) {
    for(var x = 0; x < array.length; x++) {
        document.getElementById(array[x]).onkeydown = function(e) {
            console.log(array[x]);
            console.log(array_2[x]);
            console.log(x);
            if(e.keyCode == 38 || e.which == 38) {
                this.value = ++this.value;
                document.querySelector('.input_display').innerHTML = array_2[x] + ' on arrow up';
            } else if(e.keyCode == 40 || e.which == 40) {
                 this.value = --this.value;
                 document.querySelector('.input_display').innerHTML = array_2[x] + ' on arrow down';   
            };
        };
    };
};

updown(['input1', 'input2', 'input3'], ['input1 changed', 'input2 changed', 'input3 changed']);

脚本:

// same on all input fields
console.log(array[x]); // undefined
console.log(array_2[x]); // undefined
console.log(x); // 3

document.querySelector('.input_display').innerHTML // undefined on arrow up || undefined on arrow down;

结果:

// on first input field
console.log(array[x]); // input1
console.log(array_2[x]); // input1 changed
console.log(x); // 0

document.querySelector('.input_display').innerHTML // input1 changed on arrow up

// on second input field
console.log(array[x]); // input2
console.log(array_2[x]); // input2 changed
console.log(x); // 1

document.querySelector('.input_display').innerHTML // input2 changed on arrow down;

// on third input field
console.log(array[x]); // input3
console.log(array_2[x]); // input3 changed
console.log(x); // 2

document.querySelector('.input_display').innerHTML // input3 changed on arrow up 

预期结果:

x < array.length

条件指定array.length = 3,其中x。因此,2的最大值应为x = 3。同时,console.log定义了undefined。 而且我非常确定,该值之所以为console.log(array[x])返回array[3]的原因是因为它试图获取不存在的onkeypress

如果实际上没有发生循环,则输入字段将不会侦听任何事件,因为是将事件侦听器附加到输入字段的循环。但是,由于输入字段正确侦听了x > 2事件,那么控制台为什么返回x = 3?以及为什么每个输入都返回相同的索引input1而不是x = 0具有input2x = 1具有input3x = 2具有{{1 }}?使用类似方法可以解决此问题吗?

0 个答案:

没有答案