Reputation: 13233
When I try to return
a value from a function that uses $.each()
I get undefined
instead of the value. But when I return it directly from the function, it finds the value. Strange behaviour that I'm not familiar with how to resolve.
I made a fiddle here which is an example of this issue: JS Fiddle
function returneach() {
$("b").each(function(i,v){
if(i==3) { alert('should be: ' + i); return i; }
});
}
alert('but returns: ' + returneach()); // <- undefined
How do I get this working like it should?
Upvotes: 0
Views: 72
Reputation: 10677
You have two nested functions here.
Your return
inside the inner function will not cause the outer function to return.
Use a variable and return that variable:
function returneach() {
var r;
$("b").each(function(i,v){
if(i==3) r = i;
});
return r; // This will either return 3 or undefined
}
Upvotes: 2
Reputation: 3702
A lot of times, iterating over a collection involves returning another collection or array. Here's an updated fiddle showing that
function returneach() {
var arr = [];
$("b").each(function(i,v){
if(i==3 || i == 2) { console.log('should be: ' + i); arr.push(i); }
});
return arr;
}
console.log('but returns: ' + returneach());
Added function using $.map()
as per advice from comments.
function returneachWithMap(){
return $.map($('b'), function(i,v){
if(v==3 || v == 2) { console.log('should be: ' + v); return v; };
});
}
console.log('but returns: ' + returneachWithMap());
Also, the title of the post doesn't reflect the code you are using. $.each()
is not the same thing as $(selector).each()
. From the jQuery docs:
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array
Upvotes: 0
Reputation: 6349
Or you can do something like this
function returneach() {
var allTags$ = $("b");
for(var i=0; i<allTags$.length; i++ ){
if(i==3) {
return i;
}
}
}
alert('but returns: ' + returneach());
Upvotes: 1
Reputation: 8340
You have to return a value from returneach()
function returneach() {
var retVal;
$("b").each(function (i, v) {
if (i == 3) {
alert('should be: ' + i);
retVal = i;
}
});
return retVal;
}
alert('but returns: ' + returneach()); // <- undefined
Upvotes: 0
Reputation: 9614
Assign the index to a variable and then return it
function returneach() {
var ret;
$("b").each(function(i,v){
if(i==3) {
ret = i;
}
});
return ret;
}
alert('but returns: ' + returneach());
Upvotes: 0