尝试使用Javascript函数创建计算器应用程序时出错



我试图使一个函数,只接受数字和文本字段中的一些特殊字符,但它接受我按下的任何键,即使它不在我施加的条件下,我通过onkeydown在html输入中调用该函数,我称之为id "resultado">

const numPress = (evt) =>{
let charCode = evt.keyCode || evt.which;
let charStr = String.fromCharCode(charCode);
let allowedKeys = ["+", "-", "*", "/"]
let currentValue = document.getElementById('resultado').value
if (evt.keyCode === 8)
{
currentValue = currentValue.slice(0,-1);
console.log('Apagou!')    
} 
else if (!isNaN(parseInt(charStr) || allowedKeys.includes(charStr) )) 
{
console.log(currentValue)
currentValue += charStr
} else{
currentValue = 'Error'
}
}

'我希望它只接受数字和我的allowedKeys(+, -,/, *)中列出的键,但它接受任何键

第二个条件中括号放错了地方。应该是:

else if (!isNaN(parseInt(charStr)) || allowedKeys.includes(charStr))

您当前正在传递parseInt(charStr) || allowedKeys.includes(charStr)作为isNaN的参数。

相关内容

最新更新