简体   繁体   中英

How to loop through array and check array values

so I have an Array and I want to loop through the Array and check if the values in it match some strings and if so do something.

This is what I have so far:

var rgt_count = a_related_genres_leon.length; // <- 3 items

for (var i = 0; i < rgt_count; i++) {

    if inArray("Music", a_related_genres_leon) {
        console.log('Music');
    } else if inArray("TV", a_related_genres_leon) {
        console.log('TV');
    } else if inArray("Comedy", a_related_genres_leon) {
        console.log('Comedy');
    }
}

I'm getting a Uncaught SyntaxError: Unexpected token ( error right now.

I also tried this

if text($.inArray("Music", a_related_genres_leon)) {
        console.log('Music');
    } else if text($.inArray("TV", a_related_genres_leon)) {
        console.log('TV');
    } else if text($.inArray("Comedy", a_related_genres_leon)) {
        console.log('Comedy');
    }

Either search for a particular element in the array:

if ($.inArray("Music", a_related_genres_leon) > -1) {
    console.log('Music');
}
if ($.inArray("TV", a_related_genres_leon) > -1) {
    console.log('TV');
}
if ($.inArray("Comedy", a_related_genres_leon) > -1) {
    console.log('Comedy');
}

or iterate over all elements in the array

var rgt_count = a_related_genres_leon.length; // <- 3 items
for (var i = 0; i < rgt_count; i++) {
    console.log(a_related_genres_leon[i]);
}

but do not do a mixture of both.

Refer this for correct syntax and usage

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/if...else http://api.jquery.com/jQuery.inArray/

if($.inArray("Music", a_related_genres_leon) > -1) {
    console.log('Music');
} else if($.inArray("TV", a_related_genres_leon) > -1) {
    console.log('TV');
} else if($.inArray("Comedy", a_related_genres_leon) > -1) {
    console.log('Comedy');
}

Try this:

if ($.inArray("Music", a_related_genres_leon) > -1) {
    console.log('Music');
} else if ($.inArray("TV", a_related_genres_leon) > -1) {
    console.log('TV');
} else if ($.inArray("Comedy", a_related_genres_leon) > -1) {
    console.log('Comedy');
}

From the jQuery.inArray() API Docs

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (ie 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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