I was wondering if there a more elegant way of returning a value from the function I've pasted below : "getImageURLforPOICategory".
我想知道是否有更优雅的方式从我粘贴的函数返回一个值:“getImageURLforPOICategory”。
As you can see I've used JQuery's "each" function to iterate through an array 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.
正如你所看到的,我已经使用JQuery的“each”函数来遍历一个对象数组,当我找到匹配的值时,我希望从“each”循环中返回一个结果,然后直接从包含每个循环。
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
邓肯
2 个解决方案
#1
2
No, you can't return a value from the .each()
.
不,你不能从.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:
如果你不使用$ .each(),而是使用for循环,你将能够:
return Tracker.pointofinterestcategories[ i ].imageurl
#2
0
I'd still use a for loop though.
我仍然会使用for循环。
Tracker.getImageURLforPOICategory = function (POICategoryID) {
return $.grep(Tracker.pointofinterestcategories, function (item) {
return item.id === POICategoryID;
})[0].imageurl;
}
#1
2
No, you can't return a value from the .each()
.
不,你不能从.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:
如果你不使用$ .each(),而是使用for循环,你将能够:
return Tracker.pointofinterestcategories[ i ].imageurl
#2
0
I'd still use a for loop though.
我仍然会使用for循环。
Tracker.getImageURLforPOICategory = function (POICategoryID) {
return $.grep(Tracker.pointofinterestcategories, function (item) {
return item.id === POICategoryID;
})[0].imageurl;
}