Javascript 基于KeyCode进行数组更改
我试图使用下面的代码使arrayGroup包含与上下击键相关的数据集。根据这一点,它将从名为numberray1的变量中添加或减去一个数组,并允许根据要设置的数据集arrayGroup调用不同的数组。目前,我可以将数组作为字符串调用,但在将它们作为数组调用并将其传递到arrayGroup时遇到问题 非常感谢您的建议Javascript 基于KeyCode进行数组更改,javascript,arrays,string,keydown,Javascript,Arrays,String,Keydown,我试图使用下面的代码使arrayGroup包含与上下击键相关的数据集。根据这一点,它将从名为numberray1的变量中添加或减去一个数组,并允许根据要设置的数据集arrayGroup调用不同的数组。目前,我可以将数组作为字符串调用,但在将它们作为数组调用并将其传递到arrayGroup时遇到问题 非常感谢您的建议 var arrayGroup = []; var numberArray1 = [1,2,3,4,5,6,7,8,9,10]; var numberArray2 = [10,11
var arrayGroup = [];
var numberArray1 = [1,2,3,4,5,6,7,8,9,10];
var numberArray2 = [10,11,12,13,14,15,16,17,18,19];
x=0;
alert(x);
document.addEventListener('keydown', function (evt) {
if (evt.keyCode === 38) {
alert('The "UP" key is being held down...?');
alert(numberArray1);
x=x+1;
alert(x);
alert ("numberArray"+(x));
arrayGroup = "numberArray"+(x);
alert(arrayGroup);
}
if (evt.keyCode === 40) {
alert('The "DOWN" key is being held down...?');
arrayGroup = "numberArray"+(x-1);
x=x-1;
if(x<0){
x=0;
arrayGroup = "numberArray0";
}
alert(x);
alert(arrayGroup);
}
});
var arrayGroup=[];
var numberray1=[1,2,3,4,5,6,7,8,9,10];
var numberray2=[10,11,12,13,14,15,16,17,18,19];
x=0;
警报(x);
文档.添加的EventListener('keydown',函数(evt){
如果(evt.keyCode===38){
警报(“向上”键被按下…?);
警报(1号);
x=x+1;
警报(x);
警报(“数字射线”+(x));
arrayGroup=“numberArray”+(x);
警报(arrayGroup);
}
如果(evt.keyCode===40){
警报(“按下”键…?);
arrayGroup=“numberArray”+(x-1);
x=x-1;
如果(x您正在为变量arrayGroup分配一个字符串值,这就是为什么您能够以字符串的形式访问它们。如果您想以数组的形式访问它们,只需将您想要的数组分配给arrayGroup变量,如下所示:
arrayGroup = numberArray1;
console.log(arrayGroup); // outputs: [1,2,3,4,5,6,7,8,9,10]
这样,arrayGroup[0]
将输出1
。您当前的操作方式是:
arrayGroup = "numberArray1";
console.log(arrayGroup[0]); // outputs: "n" because "n" is at index 0 of the string assigned to arrayGroup.
另外,关于增加和减少x值的一些建议:
x++; // increases the value of x by one
x += 1; // is the same as x = x + 1
x--; // decreases the value of x by one
x -= 1; // is the same as x = x -1
我想这回答了你的问题(尽我所能理解)。如果这不是您想要的,请告诉我,我会看看我是否能进一步帮助您。我希望这能帮助您!我感谢您的评论并记录下来,但我认为我的问题有点复杂。如果有机会,请查看我的更新代码。再次感谢。。。
x++; // increases the value of x by one
x += 1; // is the same as x = x + 1
x--; // decreases the value of x by one
x -= 1; // is the same as x = x -1