简体   繁体   English

javascript switch语句/大小写表达式

[英]javascript switch statement/case expression

I am using a switch statement to search for undefined values to manually change it. 我正在使用switch语句搜索未定义的值以手动更改它。 but I am having trouble using boolean expressions as I would when using an if statement. 但是我在使用布尔表达式时遇到麻烦,就像在使用if语句时那样。

Like: if statemant 像: 如果statemant

if(Item1 == undefined)
{
  item1 ="No";
}
else if (Item2 == undefined)
{
  item2 = "No";
}

etc.. 等等..

I tried this with the switch statement : 我尝试使用switch语句

 switch (array) {
 case (item1 == undefined):
 item1 = "No";
 console.log('item1 result', item1 );
 break;
 case item2 == undefined:
 item2 = "No";
 console.log('item2 result', item2 );
 break;
 default:

 }

It does not run through the switch statement, except for when I remove == undefined and only use item1 . 它不会通过switch语句运行,除非我删除== undefined且仅使用item1 then it works? 那行吗?

The switch cannot evaluate values of the array like that and that is why it does not run through the switch statement. switch无法像这样评估数组的值,这就是为什么它不通过switch语句运行的原因。 You need to define which value of that array you want to switch. 您需要定义要切换的那个数组的值。

Inside case statement you also cannot use expression, you have to use a value there as well. case statement您也不能使用表达式,您也必须在其中使用一个值。

So, if you are dead set on using switch for what you are trying to accomplish, you can do something like this: 因此,如果您不愿意使用switch来尝试完成任务,则可以执行以下操作:

item1 = array[1];
switch(item1) {
    case "undefined":
        // so on
    break;
}

But, based on your example you are probably trying to check if the values are set or not, for that if statements are still the best choice rather than switch. 但是,根据您的示例,您可能正在尝试检查是否设置了值,因此, if语句仍然是最佳选择,而不是切换。

$arr = []; // Your array
if(typeof $arr[0] == "undefined") {
    $arr[0] = "No";
}

switch can be applied only 1 variable as follows: 开关只能应用1个变量,如下所示:

switch (array) {
 case 'undefined':
 item1 = "No";
 console.log('item1 result', item1 );
 break;
 case array.length:
 item2 = "No";
 console.log('item2 result', item2 );
 break;

 }
for(var i=0;i<array.length;i++){ 
    switch(array[i])  {
    case "undefined":
   //so on
      break;
  }
}

Useful when reading arguments of function. 在读取函数的参数时很有用。

Short and simple approach would be 简短而简单的方法是

item1 = (item1 == null)? item1 : 'no';
item2 = (item2 == null)? item2 : 'no';

If item is undefined or null it will assign value otherwise that particular item. 如果undefined item或为null ,则将为该项目分配值。

ps this is for checking null or undefined and better than using switch ps这是用于检查null或undefined,并且比使用switch更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM