How to use Array and IndexOf together?

Viewed 84

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? for .e.g 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.

UPDATES- Thanks that indexOf works fine but the way I have used an array on var str doesn't seem to work.

HTML

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

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

2 Answers

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:

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

As @BenM specified, the .indexOf() method is not used this way.

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>

Related