$.each() doesn't work when only one item to loop over?
I had an each method call on some getJSON
results:
if(data && data.query && data.query.results)
{
$.each(data.query.results.span开发者_StackOverflow中文版, function(i, item)
{
console.log("Content:" + item.content); // FAILS --> UNDEFINED!!
});
}
I couldn't figure out why it wouldn't display anything even though I could see JSON returning a single result.
So I removed each and did this:
if(data && data.query && data.query.results)
{
console.log("Content:" + data.query.results.span.content); // WORKS!!
}
Now it works.
Is there no way to use each()
when there is only a single result?
$.each
expects an array in the first argument, so something like this:
$.each([ data.query.results.span ], function(i, item) { ... }
should work. The square brackets create a single item array.
If the first argument of $.each()
is not an array, then it will iterate over the properties (for lack of a better term) of the object.
For instance:
var a = {first: "abc", second: "def"};
$.each(a, function(i, item){...});
The function passed into $.each
will be called twice. The first time, i will be "first" and item will be "abc". The second time i will be "second" and item will be "def".
Doublecheck the collection first, if it is already an array of objects. If not, overwrite your variable nested in itself as an array of objects:
if (MyCollection[0]==undefined) MyCollection = [MyCollection];
$.each(MyCollection, function (key,item) { ....
精彩评论