Javascript 查找包含单词的特定链接并添加到数组

Javascript 查找包含单词的特定链接并添加到数组,javascript,Javascript,我正在尝试搜索包含单词playgame的链接页面。如果它们找到了,那么我将它们添加到一个数组中。然后从数组中选择一个随机值并使用window.location。我的问题是它说我的indexof未定义。我不确定这到底意味着什么,因为我还在学习使用javascript的这个特性 链接示例 <a href="playgame.aspx?gid=22693&amp;tag=ddab47a0b9ba5cb4"><img src="http://games.mochiads.com

我正在尝试搜索包含单词playgame的链接页面。如果它们找到了,那么我将它们添加到一个数组中。然后从数组中选择一个随机值并使用
window.location
。我的问题是它说我的
indexof
未定义。我不确定这到底意味着什么,因为我还在学习使用javascript的这个特性

链接示例

<a href="playgame.aspx?gid=22693&amp;tag=ddab47a0b9ba5cb4"><img src="http://games.mochiads.com/c/g/running-lion-2/_thumb_100x100.jpg"></a>
我的问题是它说我的indexof是未定义的

而不是
indexOf
,您正在调用它的东西
gameLinks
是一个
NodeList
,它没有
href
属性。您需要循环浏览列表的内容以查看单个元素的
href
属性。例如:

var index, href, links, randomHref, gameLinks;
gameLinks = document.getElementsByTagName("a");
// Loop through the links
links = [];
for (index = 0; index < gameLinks.length; ++index) {
    // Get this specific link's href
    href = gameLinks[index].href;
    if (href.indexOf("playgame") != -1) {
        links.push(href);
    }
}
randomHref = links[Math.floor(Math.random() * links.length)];
window.location = randomHref;
var索引,href,links,randomHref,gameLinks;
gameLinks=document.getElementsByTagName(“a”);
//循环浏览链接
链接=[];
对于(索引=0;索引
更多信息可供探索:


谢谢,是的,我忘了为这些变量添加
var
。我更新了我的帖子。我正在测试您的代码,但数组中只填充单词undefined。这是否意味着找不到“playgame”字符串?@Mr.1.0-在T.J.的代码中,
links.push(gameLinks.href)应该是
links.push(href)。我已经编辑了T.J.的代码以进行更正。非常感谢你们的时间和帮助。非常感谢。@jfriend00:谢谢你能听到。@Mr.1.0:不用担心。FWIW,把
var
放在你的代码上不是最好的做法,因为这会误导你
var
应该位于函数的顶部(或全局范围的顶部,但实际上最好不要有全局变量)。原因如下:。
var index, href, links, randomHref, gameLinks;
gameLinks = document.getElementsByTagName("a");
// Loop through the links
links = [];
for (index = 0; index < gameLinks.length; ++index) {
    // Get this specific link's href
    href = gameLinks[index].href;
    if (href.indexOf("playgame") != -1) {
        links.push(href);
    }
}
randomHref = links[Math.floor(Math.random() * links.length)];
window.location = randomHref;