1

我将如何将其重写ifelse为 a switch

var d = document,
    a = 'foo',
    b = 'bar',
    c = 'foobar';

if (d.URL.indexOf(a) != -1 || d.URL.indexOf(b) != -1)
{

    // do this

}
elseif(d.URL.indexOf(c) != -1)
{

    // do something else

}

它持续了大约 10 个ifelse,这就是为什么我更愿意将其更改为switch

我已经搜索了答案,但一无所获,所以尝试了这个:

function io(i)
{
    d.URL.indexOf(i) != -1;
}

switch (io())
{
case a:
case b:
    // do this
    break;
case c:
    // do this
    break;
}

以及同一件事的一些变体,但我是一个 JS 新手,所以我知道我可能错了(我错了)。

4

1 回答 1

1

我认为最好的办法是用它们的函数实际创建一个对象数组,然后你只需使用every. 这是使用上述示例的一些演示代码:

var choices = [
  {
    value: foo,
    fn: function () { // do this }
  },
  {
    value: 'foobar',
    fn: function () { // do something else }
  }
];
choices.every( function( choice ) {
  if ( document.URL.indexOf( choice.value ) !== -1 ) {
    choice.fn();
    return false;
  } else return true;
});

如果你有知道会被多次使用的函数,你只需在数组之外创建它们并将它们分配给fn多个对象的键。通过return true在没有遇到它时使用它,它会继续在数组中移动,然后当它碰到一个它是真的时,它会return false并结束每个函数。

于 2013-10-28T02:08:26.560 回答