Most elegant way to return value from within JQuery $.each?
I was wondering if there a more elegant way of returning a value from the function I've pasted below : "getImageURLforPOICategory".
As you can see I've used JQuery's "each" function to iterate through an a开发者_开发技巧rray of objects, when I find the matching value I want to return a result out of the "each" loop and then right out of the function that contains the each loop.
I've used a local variable to "cache" it and then I'm returning that. I'm not entirely sure if this is the best approach? Is there a way of returning the value directly from within the each loop?
Tracker.getImageURLforPOICategory = function (POICategoryID) {
var url;
$.each(Tracker.pointofinterestcategories, function () {
if (this.id === POICategoryID) {
url = this.imageurl;
return;
}
}
);
return url;
};
Thanks for reading,
Cheers,
Duncan
No, you can't return a value from the .each()
.
If you do a return false;
it will stop the loop so it isn't running longer than it needs to, but you'll need to use a variable as you're doing now.
If you don't use $.each()
, but instead use a for
loop, you'll be able to just:
return Tracker.pointofinterestcategories[ i ].imageurl
I'd still use a for loop though.
Tracker.getImageURLforPOICategory = function (POICategoryID) {
return $.grep(Tracker.pointofinterestcategories, function (item) {
return item.id === POICategoryID;
})[0].imageurl;
}
精彩评论