Why does this not work?
var animals = ['Cat', 'Dog'].valueOf;
if ("animals:contains(Cat)") {
// ...
}
Why does this not work?
var animals = ['Cat', 'Dog'].valueOf;
if ("animals:contains(Cat)") {
// ...
}
You want to use the indexOf
method of Array
:
if(animals.indexOf('Cat') != -1){
// ...
}
Any string that isn't empty (""
) will be truthy, so the body of the if
will always run if you do if("some string")
.
You can't use a CSS selector on an array in Javascript. You can use indexOf
to see if a particular string exists in the array.
if (animals.indexOf('Cat') > -1) {
console.log('We have kitties.')
}
The only time you'd really use a CSS selector in Javascript is when you're querying the DOM.
It seems you want something like JSONSelect:
JSONSelect defines a language very similar in syntax and structure to CSS3 Selectors. JSONSelect expressions are patterns which can be matched against JSON documents.
Note that :contains
is not a standard CSS psedo-class, but JSONSelect provides it as an extension.
var animals = ['Cat', 'Dog'];
if (JSONSelect.match(':contains("Cat")', animals).length) // truthy
document.write('There is a cat');
if (JSONSelect.match(':contains("Elephant")', animals).length) // falsy
document.write('There is an elephant');
<script src="http://jsonselect.org/js/jsonselect.js"></script>
But of course, this is overkill. Better use approaches explained in How do I check if an array includes an object in JavaScript?.