JavaScript switch 语句是线性的还是恒定的时间? [英] Is JavaScript switch statement linear or constant time?
问题描述
我的网站上有以下 JavaScript,以便在执行某些特定搜索时,答案被硬编码到特定页面:
I have the following JavaScript on my site so that when certain specific searches are performed, the answer is hardcoded to a specific page:
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
}
我想知道 JavaScript 中的搜索语句是否与 case 语句的数量或常数时间成线性关系?如果是线性的,是否有更好的方法来编写此代码,无论我编写多少特殊情况,它都是恒定时间?
I'm wondering whether the search statement in JavaScript is linear on the number of case statements or constant time? If linear, is there a better way to write this code so it is constant time regardless of the number of special cases I code?
推荐答案
这里相当于 Bergi 在 ES5 中的回答.与您现在使用的相比,它会更快且更容易修改.
Here's the equivalent of Bergi's answer in ES5. It'll be fast and also a lot easier to modify compared to what you're using now.
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;
}
这篇关于JavaScript switch 语句是线性的还是恒定的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!