在javascript中检查数组中的值?
我有一个:在javascript中检查数组中的值?,javascript,Javascript,我有一个: var pageURL = location.href; // stores the URL of the current page in the var pageURL 我有: var Page = Array (); page [0] = "http://web1.com" page [1] = "http://web2.com" page [2] = "http://web3.com" 现在我想做一个函数(称为nextPage)来检查数组中的哪一个页面等于PageURL。此
var pageURL = location.href; // stores the URL of the current page in the var pageURL
我有:
var Page = Array ();
page [0] = "http://web1.com"
page [1] = "http://web2.com"
page [2] = "http://web3.com"
现在我想做一个函数(称为nextPage)来检查数组中的哪一个页面等于PageURL。此外,我需要有一个按钮,所以当我点击它将带我到下一页。这意味着我想将页面增加1。
您可以非常简单地使用
var current = page.indexOf(location.href);
然后转到下一页
location.href = page[current + 1];
根据Joseph的回答,完整代码如下所示:
function goToNextPage() {
var currentPageUrl = location.href;
var pageUrls = [
"http://web1.com",
"http://web2.com",
"http://web3.com"
];
var currentIndex = pageUrls.indexOf(location.href);
var nextIndex = currentIndex + 1;
var nextPageUrl = pageUrls[nextIndex];
location.href = nextPageUrl;
}
另外,如果在IE中对indexOf的支持是一个问题,请查看另一个StackOverflow问题的答案:在数组中循环是一项相当基本的编程任务。我可能会建议您阅读一些教程,或者使用此polyfill来使用ES5
数组.prototype.indexOf
:@AtesGoral,大多数情况下都是这样。事实上,除了IE之外,它在大多数浏览器中都有很好的支持。不过,即使在那时,它现在也是如此。@JosephMarikle,我听到了。但不幸的是,“大部分”并没有在野外进行切割。您要么是跨浏览器,要么不是跨浏览器。您可以设置:page[(当前+1)%page.length]
,这样它就不会在最后一页导航到未定义,而是换行到第一页。@JosephMarikle正确的做法是在有多边形填充的情况下使用indexOf
,直到有合理比例的浏览器开始支持它。你还不能排除function goToNextPage() {
var currentPageUrl = location.href;
var pageUrls = [
"http://web1.com",
"http://web2.com",
"http://web3.com"
];
var currentIndex = pageUrls.indexOf(location.href);
var nextIndex = currentIndex + 1;
var nextPageUrl = pageUrls[nextIndex];
location.href = nextPageUrl;
}