-2

也许我忘记了某种规则。告诉我想做什么应该很明显。似乎无论为“sph”变量输入和存储什么,我得到的唯一警报都是第一个。如果有的话,我希望'else'语句起作用。我尝试了不同的方法,例如使用 '==' 和 '===' 运算符。我还将它更改为“switch”语句,使用“if”而不是“else if”,并且还尝试了嵌套。我没有看到任何语法错误,所以我的下一个猜测是我无法以我尝试的方式访问数组。

注意:第二个提示输入意为负数;如果你想知道为什么我有'cyl <= 0'。

var sph = prompt("What is the sphere power?");
var cyl = prompt("What is the cylinder power?");

var sixSevenFive = [6.5, 6.25, 6];
var six = [5.75, 5.5, 5.25];
var five = [5, 4.75, 4.5, 4.25];
var fourFive = [4.0, 3.75, 3.5];
var four = [3.25, 3.00, 2.75, 2.5, 2.25, 2, 1.75, 1.5, 1.25, 1, .75, .5, .25];


if ((sph = four) && (cyl <= 0)) {
alert("Use a 4.00 Base lens.");
}

else if ((sph = fourFive) && (cyl <= 0)){
alert("Use a 4.50 Base lens.");
}

else if ((sph = five) && (cyl <= 0)){
alert("Use a 5.25 Base lens.");
}

else if ((sph = six) && (cyl <= 0)){
alert("Use a 6.00 Base lens.");
}

else if ((sph = sixSevenFive) && (cyl <= 0)){
alert("Use a 6.75 Base lens.");
}

else {
alert("You entered an invalid prescription.");
}
4

4 回答 4

3

=当您需要运算符时,您已经重复使用了运算==符。第一个分配一个值。第二个是测试。===还测试数据类型是否相同,通常更可取。

和 bfavaretto 的观点。

于 2013-08-11T20:57:07.460 回答
2

您不能使用相等运算符(=====,而不是=!)来检查数组中的值。改用这样的东西:

if(four.indexOf(sph) > -1 && cyl <= 0) { // etc

此外,parseFloat在您的输入中使用以确保您将数字与数字(而不是字符串)进行比较:

var sph = parseFloat(prompt("What is the sphere power?"));
var cyl = parseFloat(prompt("What is the cylinder power?"));

演示:http: //jsfiddle.net/Wmesx/

于 2013-08-11T20:59:52.080 回答
1

当您应该使用 == 或 === 运算符时,您正在使用赋值运算符。

http://www.w3schools.com/js/js_comparisons.asp

于 2013-08-11T20:56:55.920 回答
0

使用运算符测试相等性==

于 2013-08-11T20:57:33.710 回答