如何在Javascript的if语句中检查变量中的数字和运算符
我还试图找到一种方法,在两个按钮被“突出显示”并将类名更改为“duction”后,在它们之间交换文本。(这个问题与第一个问题完全无关如何在Javascript的if语句中检查变量中的数字和运算符,javascript,Javascript,我还试图找到一种方法,在两个按钮被“突出显示”并将类名更改为“duction”后,在它们之间交换文本。(这个问题与第一个问题完全无关 function AddDigit(x) { if (x == ????) {document.calculator.display.value=x;} else {document.calculator.display.value+=digit + x;} } function Evaluate() { result=eval(documen
function AddDigit(x)
{
if (x == ????)
{document.calculator.display.value=x;}
else
{document.calculator.display.value+=digit + x;}
}
function Evaluate()
{
result=eval(document.calculator.display.value);
document.calculator.display.value = result;
}
您的某些id属性无效。按惯例,以大写字母开头的函数名是为构造函数保留的 要测试参数是否为数字,请执行以下操作:
document.ondblclick=function(button)
{
clearTimeout(timer);
thing=button.target;
if(thing.className=="intro")
{thing.className="duction";}
else if(thing.className=="duction")
{thing.className="intro";}
}
function clearDigit()
{
document.calculator.display.value="";
}
编辑
一些进一步的解释。/
中的表达式是a,它创建了一个。对象的方法和对象本身可以以各种方式使用
模式^\d$
匹配的字符串正好是一个数字(0到9)。该方法根据参数是否匹配模式返回true
或false
。因此表达式:
function addDigit(x) {
if (/^\d$/.test(x)) {
// x is a single digit
}
...
}
创建一个正则表达式对象,其模式匹配一个数字,然后使用它测试提供的参数是否匹配,最后返回布尔值true
或false
您还可以使用:
但这要求x
为字符串,而test
将参数转换为字符串(如果参数不是字符串)。它还返回数组(如果找到至少一个匹配项)或null
(如果找不到匹配项)。因此,它需要将类型转换为布尔值,这不像返回布尔值的test
那样整洁
HTH.:-这里有两种方法(我相信还有更多)
这很令人困惑。请提供您的HTML和其他Javascript。把这个问题分为两个问题-你的
className
东西与你的第一个问题无关。这是一个正则表达式,JavaScript内置了对它的支持。
function addDigit(x) {
if (/^\d$/.test(x)) {
// x is a single digit
}
...
}
/^\d$/.test(x)
x.match(/^\d$/)
function AddDigit(x) {
//if it parses to an integer or is a literal '.'
if (typeof parseInt(x, 10) === 'number' || x === '.') {
//digit or decimal
document.calculator.display.value = x;
} else {
//operator: + - x /
document.calculator.display.value += digit + x;
}
}
function AddDigit(x) {
//use a RegExp
var operator = /[+-x\/]/;
if (operator.test(x)) {
//operator: + - x /
document.calculator.display.value += digit + x;
} else {
//digit or decimal
document.calculator.display.value = x;
}
}