我正在使用HTML和jQuery构建计算器。
看看我的平方根功能。当我按下sqrt按钮时,它返回NaN。为什么?我刚尝试放parseFloat(number)
,它也返回NaN。请帮帮我!
Jquery:
$(document).ready(function(){
var testNumLength = function(number) {
if (number.length > 9) {
totaldiv.text(number.substr(number.length-9,9));
if (number.length > 15) {
number = "";
totaldiv.text("Err");
}
}
};
var number = "";
var newnumber = "";
var operator = "";
var totaldiv = $("#total");
totaldiv.text("0");
$("#numbers a").not("#clear,#clearall").click(function(){
number += $(this).text();
totaldiv.text(number);
testNumLength(number);
});
$("#operators a, #side a").not("#equals, #decimal").click(function(){
operator = $(this).text();
newnumber = number;
number = "";
totaldiv.text("0");
if($(this).attr('id') === "sqrt") {
operator = "sqrt";
$("#equals").click();
}
});
$("#clear,#clearall").click(function(){
number = "";
totaldiv.text("0");
if ($(this).attr("id") === "clearall") {
newnumber = "";
}
});
//Add your last .click() here!
$("#equals").click(function(){
if (operator === "+"){
number = (parseInt(number, 10) + parseInt(newnumber,10)).toString(10);
} else if (operator === "-"){
number = (parseInt(newnumber, 10) - parseInt(number,10)).toString(10);
} else if (operator === "÷"){
number = (parseInt(newnumber, 10) / parseInt(number,10)).toString(10);
} else if (operator === "×"){
number = (parseInt(newnumber, 10) * parseInt(number,10)).toString(10);
} else if (operator === "sqrt") {
number = Math.sqrt(parseFloat(number,10)).toString(10);
}
totaldiv.text(number);
testNumLength(number);
number = "";
newnumber = "";
});
$('#decimal').click(function(){
var numOfDecs = 0;
for(var i = 0; i < number.length; i++){
if(number[i] === ".") {
totaldiv.text(number[i]);
}
}
if (numOfDecs === 0) {
number.append('.');
totaldiv.text(number);
testNumLengh(number);
}
})
});
这是一个小提琴: https://jsfiddle.net/fqdxkL4y/
答案 0 :(得分:1)
如果你alert
在这里,你会发现number
未在此传递或传递为没有价值。
else if (operator === "sqrt") {
// alert(number);
number = Math.sqrt(parseFloat(number,10)).toString(10);
}
正如SK Jajoriya所建议的那样。但请注意,您必须解决具有长号的约束。
答案 1 :(得分:1)
使用number = newnumber;而不是数字=&#34;&#34 ;;在运算符中单击函数,因为平方根函数取值为number。它适用于你的平方根函数。