简体   繁体   English

如何一起使用Array和IndexOf?

[英]How to use Array and IndexOf together?

I am trying to create an array of strings and use indexOf function to check if the text exists on <td> or not, if it does I want it to execute else do nothing? 我正在尝试创建一个字符串数组并使用indexOf函数来检查文本是否存在于<td> ,如果是,我希望它执行其他什么都不做? for .eg One exists on <td> so indexOf recognizes that executes The problem is this code is not working at the moment it was working when I was not using an array. for .eg一个存在于<td>所以indexOf识别出执行问题是当我不使用数组时,此代码在它工作时不起作用。

UPDATES- Thanks that indexOf works fine but the way I have used an array on var str doesn't seem to work. 更新 - 感谢indexOf工作正常,但我在var str上使用数组的方式似乎不起作用。

HTML HTML

<tbody>
 <td><a href='#'>One</a></td>
 <td>No.</td>
</tbody>

Jquery jQuery的

var array =  ['One', 'Two', 'Three', 'Four'];
var str = $('td:contains(" + array + ")').text();
if(array.indexOf(str) > -1){
 console.log('Array works');
}

Any help will be much appreciated 任何帮助都感激不尽

You're using it the wrong way around. 你正在以错误的方式使用它。 In this case, you want the indexOf() prototype of Array , not string, so your logic should be: 在这种情况下,您需要ArrayindexOf()原型,而不是字符串,因此您的逻辑应该是:

if( array.indexOf(str) > -1 )
{
  // Do stuff!
}

As @BenM specified, the .indexOf() method is not used this way. 正如@BenM指定的那样, .indexOf()方法不是以这种方式使用的。

Maybe this snippet will be of use : 也许这个片段会有用:

 var array = ['One', 'Two', 'Three', 'Four']; // iterate over every <td> element found in the page with the .each() function $('td').each( function(){ if(array.indexOf($(this).text()) > -1){ console.log('"' + $(this).text() + '" was found in the array'); } } ); 
 <!DOCTYPE html> <html> <head> <title>Test</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <table> <tbody> <td><a href='#'>One</a></td> <td>No.</td> </tbody> </table> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM