我有一些jQuery代码,可以在某些网页上执行某些特定操作,而不会在其他网页上加载。这是我当前运行上述代码的方法:
if ((window.location.href).indexOf('somewebsite.com') >= 0){
chrome.extension.sendMessage({greeting: "loadscript"});
var stuff = new Stuff();
//run some code
dothiseverytime(withSomeParams);
} else if ((window.location.href).indexOf('someotherwebsite.com') >= 0){
chrome.extension.sendMessage({greeting: "loadscript"});
var stuff = new Stuff();
//run some code
dothiseverytime(withDifferentParams);
} else if
// etc..
我想知道是否可以使用indexOf和数组在切换用例的基础上做一些事情。也许与此伪代码类似?
someWebsites = ['somewebsite.com','someotherwebsite.com']
function checkTabURL {
switch ((window.location.href).indexOf(someWebsites) >= 0)
case 0 // first site in our list - index 0
var stuff = new Stuff();
// do some stuff
case 1 // second site on our list - index 1
var stuff = new Stuff();
// do some other stuff
case -1 // site isn't on the list
// don't do anything
}
我想最小化我的代码,我认为在这些方面使用某些东西也会减少编写的代码量。
由于人们会混淆我的需求并提供相反的信息(针对数组而不是针对URL搜索URL)-我想澄清一下。
我的数组可能包含“ somesite.com/subdir”之类的内容,因此我无法将URL与数组匹配-我需要将数组与URL匹配。我需要查看数组中的任何内容是否都在当前URL中(然后执行一个案例),而不是相反。
IE:当前网址中是否包含“ somesite.com/subdir”?当前网址中是否有“ someothersite.com”?对前者执行案例0,对后者执行案例1。如果没有,则为情况-1。
最佳答案
根据评论和讨论,这里是我的修改答案。首先,JavaScript中有两个indexOf
方法。一个是String Method indexOf
,它返回指定值在字符串中首次出现的位置。第二个是Array Method indexOf
,它在数组中搜索指定的项目,并返回其位置。
第一个答案为您提供了Array方法作为解决方案,但是您需要的是string方法的扩展版本。由于您不能在本地使用数组作为String方法的参数,因此需要创建一个自定义方法:
/**
* Extend the Array object
* @param needle The string to search for
* @returns Returns the index of the first match or -1 if not found
*/
Array.prototype.searchFor = function(needle) {
for (var i=0; i<this.length; i++)
if (this[i].indexOf(needle) == 0)
return i;
return -1;
};
使用这种方法(或类似的方法),您可以测试一个字符串(您的URL)是给定数组元素的部分匹配还是完全匹配。
var someWebsites = ['somewebsite.com/subdirectory','someotherwebsite.com'];
function checkTabURL(url) {
switch (someWebsites.searchFor(url)) {
case 0:
console.log('case 0');
break;
case 1:
console.log('case 1');
break;
// you can also combinate different cases:
case 2:
case 3:
// do your stuff here
break;
default:
console.log('default');
break;
}
}
// for testing: logs 0 (case 0)
// since somewebsite.com is indexOf somewebsite.com/subdirectory
checkTabURL('somewebsite.com');
//checkTabURL(window.location.href);
The new fiddle is here。
关于jquery - IndexOf和Arrays-优化此jQuery代码的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764016/