我有这个非常简单的计算器。我想把小复活节彩蛋放在代码的功能中。这是我的codepen,以显示我到目前为止所做的工作。我已经评论了我没有尝试过的尝试。我知道codepen没有显示警报,因此我尝试了实时页面,但警报仍然无效。这是javascript
// Variables
var appendDigits = false
var prevResult = 0
var op = "="
//Functions
function clearDisplay() {
document.calculator.display.value = 0
prevResult = 0
appendDigits = false
op = "="
} //clear
function doOp(newop)
{
var newArg =eval(document.calculator.display.value)
if (op == "+") {
prevResult = prevResult + newArg
}
else if (op == "-") {
prevResult = prevResult - newArg
}
else if (op == "/") {
prevResult = prevResult / newArg
}
else if (op == "*") {
prevResult = prevResult * newArg
}
else if (op == "=") {
prevResult = newArg
}
// else if (newArg == 42) {
// alert("You have found the meaning of life, the universe, and everything.");
// }
else {
prevResult = newArg
}
document.calculator.display.value = prevResult
appendDigits = false
op = newop
} //doOp
function digit(dig) {
if (appendDigits) {
document.calculator.display.value += dig
}
else {
document.calculator.display.value = dig
appendDigits = true
}
}
//fuction meaning(document.calculator.display.value)
//{
// if ( "newArg" == "42" ) {
// alert("You have found the meaning of life, the universe, and everything.");
// }
// else {
// prevResult = newArg
// }
//}
答案 0 :(得分:0)
使用它将Calculator显示值转换为int:
else if (parseInt(newArg) == 42) {
alert("You have found the meaning of life, the universe, and everything.");
}
答案 1 :(得分:0)
您需要在if / else if循环之外添加支票,以检查' op'另外一个"如果op ==" options将评估为true并结束循环。
你可以在分配newArg之后把它放好:
var newArg =eval(document.calculator.display.value)
if (newArg == 42) {
alert("You have found the meaning of life, the universe, and everything.");
}
答案 2 :(得分:0)
如果可能,尽量不要在JS中使用eval语句。这被认为是一种不好的做法 请参阅:Why is using the JavaScript eval function a bad idea?
演示:http://codepen.io/anon/pen/Kxekc
而是使用以下内容将输入转换为数字:
var newArg = parseInt(document.calculator.display.value,10);
if (newArg == 42) {
alert("You have found the meaning of life, the universe, and everything.");
}
底部的功能也有错误: // fuction的意思(document.calculator.display.value)