问题描述
我想将箭头函数语法与我一直在使用的一些代码片段一起使用。 我一直很成功,直到我特别获得了多个if语句。 我知道这可能是一个重复的问题,但是在浏览了前面的一些答案后,我仍然找不到有效的语法。
我查看了一些关于堆栈溢出的重复答案,并尝试了建议的格式,但没有任何效果。 我也没有得到任何错误。
function keydownHandler(event) {
"use strict"
// handle user keyboard input
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}
render( );
}
//===========One of many formats i've tried=============================
var keydownHandler = event => {
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}
render( );
}
1楼
您可以将具有默认功能的对象用于未知的keyCode
。
const
directions = {
UP: () => rocket.y -= velocity,
LEFT: () => rocket.x -= velocity,
DOWN: () => rocket.y += velocity,
RIGHT: () => rocket.x += velocity,
default: () => {}
};
致电
(directions[event.keyCode] || directions.default)();
2楼
如果要将其转换为1线性,可以使用 。 虽然一次只允许按一次键
const keydownHandler = (event) => {event.keyCode === UP ? rocket.y -= velocity : event.keyCode === LEFT ? rocket.x -= velocity : event.keyCode === DOWN ? rocket.y += velocity : event.keyCode === RIGHT ? rocket.x += velocity : 0; render();}
此代码未经测试。
但是出于可读性考虑,我建议使用switch语句或部分三元运算
const keydownHandler = (event) => {
// this prevents the rocket from going up and down at the same time
rocket.y += event.keyCode === UP ? velocity : event.keyCode === DOWN ? -velocity : 0;
// this prevents the rocket from going left and right at the same time. if both keys are pressed the rocket will turn right
rocket.x += event.keyCode === RIGHT ? velocity : event.keyCode === LEFT ? -velocity : 0;
render();
};
这部分代码将防止火箭同时上下运动。 如果同时按下两个键,它将上升。 左右也一样。