var startX = 501;
var finalX = 320;
var multiply = .01;
var res = finalX - startX;
var extract = multiply * res;
var toEval;
if (res > 0) {
toEval = "<=";
} else {
toEval = ">=";
}
console.log("extract= " + extract + "");
while (eval(startX + toEval + finalX)) {
startX += (-1.81);
console.log(startX + " " + extract);
}
“问题”在while循环中,在第13次迭代中,这在控制台中发生:
482.9 -1.81
proof2.html:39 481.09 -1.81
proof2.html:39 479.28 -1.81
proof2.html:39 477.46999999999997 -1.81
proof2.html:39 475.65999999999997 -1.81
479.28-1.81 = 477.47
那么循环中到底发生了什么?
最佳答案
您可以使用函数进行比较,而不使用eval
。
var startX = 501,
finalX = 320,
multiply = .01,
res = finalX - startX,
extract = multiply * res,
toEval;
if (res > 0) {
toEval = function (a, b) { return a <= b; };
} else {
toEval = function (a, b) { return a >= b; };
}
console.log("extract= " + extract + "");
while (toEval(startX, finalX)) {
startX += (-1.81);
console.log(startX + " " + extract);
}
关于javascript - 求和循环的正确方法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38337623/