If found in object, use another property in jQuery
I have this Object:
Object ->
Content: <h1>some html</h1>
Url : A url
Now i'm using this code to work out if a certain URL exists in the current object:
var inURLArray = function(url, array) {
for(var开发者_如何学C i in array) {
if(array[i].url && array[i].url == url)
return true;
}
return false;
};
So i pass it the url i'm looking for and the object i'm looking in. I can then do var found = inURLArray('http://google.com', tabArray);
what could i do if i find the URL i'm looking for to get the content in the same Object. The array is called tabArray. I'm using jQuery/Javascript!
I should say, i dont really mind how i access the content, ie. if its stored in a variable or alerted!
You could replace the boolean function by one that simply returns the object found, or null if there isn't one:
var findInArrayByUrl = function(url, array)
{
for(var i in array)
{
if(array[i].url && array[i].url == url)
{
return array[i];
}
}
return null;
};
Try this;
function getObjectInArrayByUrl (url, arr) {
var i
, obj
, arrLength = arr.length;
// loop the array
for (i = 0; i < arrLength; i++) {
// store the object in a var to save lookups
obj = arr[i];
// if obj.url isn't present or doesn't match, skip
if (!('url' in obj) || obj.url != url) {
continue;
}
// otherwise return the matching object
return obj;
}
// otherwise return fail
return null;
};
精彩评论