JavaScript 在字符串大小写上切换大小写比较行为



我有一个开关语句,它正在传递其中两种情况,而不仅仅是我预期的一种情况:

let name = 'John';
switch (name)
{
case 'john' : 
alert('Condition 1 is true.');
case 'John' : 
alert('Condition 2 is true');
case 'JOHN' :
alert('Condition 3 is true');
}

我得到的结果:

条件 2 为真

条件 3 为真

为什么我得到这个结果,我不明白?

您需要用break语句结束每个case

let name = 'John';

switch (name)
{
case 'john' : 
alert('Condition 1 is true.');
break;
case 'John' : 
alert('Condition 2 is true');
break;
case 'JOHN' :
alert('Condition 3 is true');
break;
}

let name = 'John';
switch (name)
{
case 'john' : 
alert('Condition 1 is true.');
break;
case 'John' : 
alert('Condition 2 is true');
break;
case 'JOHN' :
alert('Condition 3 is true');
break;
}

你错过了break.

最新更新