if/else 语句改为 switch

if/else statement instead switch

我有这个 ajax 请求:

    SJA.ajax(dataToSend, //this is internal method, which sends requests to the urls  
function (respond) {

      var categorySelect = that.$modal.find('.cat-post')[0].selectize; //using selectize.js plugin for selects. 

          if (respond) {
          callback && callback(respond);
          for (var i in respond) {
            //console.log(respond[i].id);
            //console.log(respond[i].name);
            categorySelect.addOption({value: respond[i].id, text: respond[i].name}); //adding new options to a select field.
          }
        }
    });
  var category: that.$modal.find('.cat-post').val() //this is option value in select field !== 'null' ? $('.cat-post').val() : null, //this variable is responsible for keeping selected data. 

然后我比较选定的数据(因为我需要获取一些字符串值才能在 table 中使用它):

var categoryName = 'all';
        switch (category) {
          case '0' // compare with respond id: 
            categoryName = "all" // compare with respond name ;
            break;
          case '1':
            categoryName = "Health";
            break;
          case '2':
            categoryName = "Cars";
            break;
        }

然后我在 table 中添加了新的 td。

  $tbody.append(['<tr data-id="' + row.id + '">',
'<td class="restricted-view-hide view-mode2-hidden view-mode21-hidden">'  + categoryName + '</td>', '</tr>'].join(''));

但我不想每次都在 switch 中输入新值,我想使用一些东西来动态接收新值。 我试过这样的事情:

categoryName = respond[i].id != null ? respond[i].name : "any";

但它不起作用。有任何想法吗?

不知道它是否可以改变任何东西,但请尝试:

categoryName = (respond[i].id != null) ? respond[i].name : "any";

也许 ^^

没错。假设:

1) 您知道您 posted 的条件语句使用 respond.id 和 respond.name,其中您的 switch 语句使用 $(".cat-post").val(),而且这两种方法很可能return完全不同的值。

2) 你 posted 的条件语句使用了你希望它使用的变量,它只是没有给出预期的答案——也就是说,在 respond.id 不是的情况下它没有给你 "any".

是有效的

如果是这种情况,那么解决方法就很简单了。没有id的元素 returns "" for .id, not null, 所以检查是否 respond.id != "", not != null.

categoryName = respond[i].id != "" ? respond[i].name : "any";

也就是说...

categoryName = respond[i].id != null ? respond[i].name : "any";

这看起来不对劲。它基本上说 "If my respond element has an id, then use its name value as categoryName"。这是你想要的吗?如果 respond[i].id 有效,您能确定 respond[i].name 将始终有效吗?为什么不检查 respond[i].name 是否为 != ""?如果未设置 id 属性,是否会对 name 属性的有效性产生疑问?使用

categoryName = respond[i].name != "" ? respond[i].name : "any";

会出现在面值上更有意义。

同样值得注意的是,假设 1) 是一个相当大的假设。如果您的代码当前按您希望的方式工作,但您想让它更灵活,除非有一些严重的数据重复(其中 $(.cat-post)[0].val( ) 设置为由 respond[i].name 确定的某个值(反之亦然)),实现你上面的内容会破坏你的代码。

请注意,这仅适用于您的代码基本上可以正常工作但给您的值错误的情况。如果它坏了,根本没有给你任何回应,那么你需要更具体地说明 "it doesn't work".

的意思