JavaScript switch 语句是线性的还是恒定时间的?

Wil*_*mKF 5 javascript time-complexity switch-statement constant-time

我的网站上有以下 JavaScript,以便在执行某些特定搜索时,答案会被硬编码到特定页面:

function redirect() {
    var input = document.getElementById('searchBox').value.toLowerCase();

    switch (input) {
      case 'rectangular':
        window.location.replace('http://www.Example.com/Rectangular/');
        break;
      case 'elephant':
        window.location.replace('http://www.Example.com/Elephants/');
        break;
      case 'coils':
        window.location.replace('http://www.Example.com/Parts/');
        break;
      default: // No keyword detected: submit the normal search form.
        return true;
        break;
    }
    return false; // Don't let the form submit
}
Run Code Online (Sandbox Code Playgroud)

我想知道 JavaScript 中的搜索语句是否与 case 语句的数量或恒定时间呈线性关系?如果是线性的,是否有更好的方法来编写此代码,以便无论我编码的特殊情况有多少,它都是恒定时间?

Mar*_*ton 2

这相当于 Bergi 在 ES5 中的答案。与您现在使用的相比,它会更快并且更容易修改。

var _redirectlist = {
  'rectangular': 'http://www.Example.com/Rectangular/',
  'elephant': 'http://www.Example.com/Elephants/',
  'coils': 'http://www.Example.com/Parts/'
};

function redirect() {
  var input = document.getElementById('searchBox').value.toLowerCase();

  // Redirect if we have the input in our list
  if (_redirectlist.hasOwnProperty(input)) {
    window.location.replace(_redirectlist[input]);
    return false;
  }

  return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,想一想,我想我知道为什么 Bergi 添加了 hasOwnProperty... 因为 Object.prototype 中的值。当你像这样直接接受用户输入时,是的,你想确保他们不会输入一些奇怪的东西。就像原型一样,通常会通过 truesy 测试。 (2认同)