OR 语句被忽略
OR statement being ignored
我试图仅在按下某些键时才触发我的 masterFunction。但是,无论单击哪个按钮,它都会被调用。即使控制台日志显示不同的密钥。
谁能指点一下?
//Update display on keydown event
addEventListener('keydown', (e) => {
pressedKey = event.key;
console.log(pressedKey);
keyDownOperatorMapping(e);
});
let keyDownOperatorMapping = (e) => {
if (pressedKey === "+" || "-" || "*" || "Enter" || "Backspace" || "." || "/") {
masterFunction(e);
}
};
您必须输入要比较的变量。在您的情况下,pressedKey
:
if (pressedKey === "+" || pressedKey === "-" || pressedKey === "*" || pressedKey === "Enter" || pressedKey === "Backspace" || pressedKey === "." || pressedKey === "/")
...
因为你现在的状态是
嘿是 pressedKey equal is "+"
或者是 "-" is true
或者 //继续
因为长度大于 1 的字符串总是 1,所以它总是 return true
你的条件总是正确的
所以一种存档方式
addEventListener('keydown', (e) => {
pressedKey = event.key;
console.log(pressedKey);
keyDownOperatorMapping(e);
});
let keyDownOperatorMapping = (e) => {
const keys = ["+", "-", "*", "Enter", "Backspace", ".", "/"]
if (keys.includes(pressedKey)) {
console.log("Found");
}
};
您可以通过将可搜索键添加到数组中来稍微减少代码,然后检查数组 includes
是否为输入的键。
const allowed = ['+', '-', '*', 'Enter', 'Backspace', ',', '/'];
document.addEventListener('keydown', (e) => {
const { key } = e;
if (allowed.includes(key)) {
// masterFunction(e)
console.log(key);
}
});
其他文档
我试图仅在按下某些键时才触发我的 masterFunction。但是,无论单击哪个按钮,它都会被调用。即使控制台日志显示不同的密钥。
谁能指点一下?
//Update display on keydown event
addEventListener('keydown', (e) => {
pressedKey = event.key;
console.log(pressedKey);
keyDownOperatorMapping(e);
});
let keyDownOperatorMapping = (e) => {
if (pressedKey === "+" || "-" || "*" || "Enter" || "Backspace" || "." || "/") {
masterFunction(e);
}
};
您必须输入要比较的变量。在您的情况下,pressedKey
:
if (pressedKey === "+" || pressedKey === "-" || pressedKey === "*" || pressedKey === "Enter" || pressedKey === "Backspace" || pressedKey === "." || pressedKey === "/")
...
因为你现在的状态是
嘿是 pressedKey equal is "+"
或者是 "-" is true
或者 //继续
因为长度大于 1 的字符串总是 1,所以它总是 return true 你的条件总是正确的
所以一种存档方式
addEventListener('keydown', (e) => {
pressedKey = event.key;
console.log(pressedKey);
keyDownOperatorMapping(e);
});
let keyDownOperatorMapping = (e) => {
const keys = ["+", "-", "*", "Enter", "Backspace", ".", "/"]
if (keys.includes(pressedKey)) {
console.log("Found");
}
};
您可以通过将可搜索键添加到数组中来稍微减少代码,然后检查数组 includes
是否为输入的键。
const allowed = ['+', '-', '*', 'Enter', 'Backspace', ',', '/'];
document.addEventListener('keydown', (e) => {
const { key } = e;
if (allowed.includes(key)) {
// masterFunction(e)
console.log(key);
}
});
其他文档