切换状态javascript

时间:2015-07-20 17:06:53

标签: javascript switch-statement

我制作了这段代码,但它根本不起作用
我应该使用switch语句
你能告诉我哪里出错了
感谢战利品:)




  var side == parseInt(prompt('输入3到10之间的数字:'));
 var shape == ['triangle', 'square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'];
 switch(shape){
 case == 3:&#xA ; shape = [0];
 break;
 case == 4:
 shape == [1];
 break;
 case == 5:&# xA; shape == [2];
 break;
 case == 6:
 shape == [3];
 break;
 case == 7: 
 shape == [4];
 break;
 case == 8:
 shape == [5];
 break;
 case == 9:
 shape == [6];
 break;
 case == 10:
 shape == [7];
 break;
} 
警告('形状是'+形状); 
  



5 个答案:

答案 0 :(得分:1)

您正在使数组shape=[0];不引用具有值的数组。

答案 1 :(得分:1)

你有很多语法错误:

case== 3:

应该只是

case 3:

shape==[1];

==测试质量,因此您基本上是在说shape is the same as an array containing the number 1

答案 2 :(得分:0)

当您使用==时,您正在使用=。在您的交换机中,您要检查用户输入(side),然后只需要选项无符号。最后,需要将形状重新分配给数组中的值。

var side = parseInt(prompt('Enter a number of side between 3 and 10: '));
var shape =['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'];
switch (side){
case 3:
shape=shape[0];
break;
case 4:
shape=shape[1];
break;
case 5:
shape=shape[2];
break;
case 6:
shape=shape[3];
break;
case 7:
shape=shape[4];
break;
case 8:
shape=shape[5];
break;
case 9:
shape=shape[6];
break;
case 10:
shape=shape[7];
break;
}
alert('The shape is ' + shape); 

答案 3 :(得分:0)

停止使用==代替=

==是比较检查,=是一个赋值运算符。

使用开关:

var side = parseInt(prompt('Enter a number of side between 3 and 10')),
shapes = ['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'],
shape;
switch (side){
case 3:
    shape = shapes[0];
    break;
case 4:
    shape = shapes[1];
    break;
case 5:
    shape = shapes[2];
    break;
case 6:
    shape = shapes[3];
    break;
case 7:
    shape = shapes[4];
    break;
case 8:
    shape = shapes[5];
    break;
case 9:
    shape = shapes[6];
    break;
case 10:
    shape = shapes[7];
    break;
}
alert('The shape is ' + shape); 

更好的方法:

var side = parseInt(prompt('Enter a number of side between 3 and 10')),
shapes =    ['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'];

alert('The shape is' + shapes[side - 3]); 

答案 4 :(得分:0)

您不需要switch语句 - 您可以使用更短更简洁的代码。您可以只指定形状,但请确保检查提示侧是否在范围内。

var shape = ['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','decagon'];

var side = parseInt(prompt('Enter a number of side between 3 and 10: '));

var userShape = shape[side - 3];

if (side < 3 || side > 10) {
    alert('Not a recognised shape')
} else {
    alert(userShape);
}

除非您确定不再使用shape数组,否则最好将检查数组的结果分配给新变量(此处{{1否则你只是覆盖了数组。

另外,十边形是十字形:)

DEMO