Does Javascript have a contains function?
I am not sure if it does or does not. Some sites show using a contains in javascript but when I try it does not work.
I have
var userAgent = navigator.userAgent.split(';');
if (userAgent.contains("ms开发者_如何学Goie7") == true) {...}
I am trying to use the useragent to figure out if the user is running IE 8 in compatibility mode. So I want to check the userAgenet for msie7 & for the trident 4.0
So how could I check this array?
There is no native Array.prototype.contains
in ES v3 ( most JS implementations ). There is an Array.prototype.indexOf available in Mozilla/Firefox and other modern JS engines which choose to adopt it.
You can use the code below to implement it on browsers/engines that dont have it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf
Then after assigning it you can do Array.prototype.contains = function(s) { return this.indexOf(s) !== -1 }
You can use indexOf
to get the index in the array which contains the element you're looking for. So you could rewrite your if
statement like this:
if (userAgent.indexOf("msie7") > -1) {...}
Note that IE (at least IE6) doesn't support indexOf
for arrays (it does work on strings though), but you could always write your own version:
if (typeof Array.prototype.indexOf == 'undefined')
Array.prototype.indexOf = function(e) {
for (var i = 0; i < this.length; i++)
if (this[i] == e)
return i;
return -1;
}
In the end I found out that jquery has a method called inArary and I used this. So I should not have to worry about compatibility issues.
Mootools is one library that can help you write better cross browser javascript. It augments javascript basic types(strings, arrays, numbers, etc) with convenient methods like 'contains'.
Or, you can implement it yourself as seen in the other answers.
You can always roll out your own contains() which will work on Array objects on all browsers.
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
Caveat: "Extending the javascript Array object is a really bad idea because you introduce new properties (your custom methods) into for-in loops which can break existing scripts."
Better use the functions provided by a mainstream library such as jQuery.
Full discussion on this topic: Javascript - array.contains(obj)
You could skip the array and test the string directly, like this:
if (navigator.userAgent.indexOf('msie') != -1)
// ...
Here's some some information on indexOf.
精彩评论