Home  >  Article  >  Web Front-end  >  JQuery $.each traverses JavaScript array object instances_jquery

JQuery $.each traverses JavaScript array object instances_jquery

WBOY
WBOYOriginal
2016-05-16 16:38:201248browse

View a simple jQuery example to iterate over a JavaScript array object.

var json = [
{"id":"1","tagName":"apple"},
{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},
{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}
];

$.each(json, function(idx, obj) {
alert(obj.tagName);
});

The above code snippet works fine, prompting “apple”, “orange”…etc., as expected.
Problem: JSON string

The following example declares a JSON string (enclosed in single or double quotes) directly.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(json, function(idx, obj) {
alert(obj.tagName);
});

In Chrome it shows the following error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for '156'
in [{"id":"1","tagName":"apple"}...

Solution: Convert JSON string to JavaScript object.
To fix it, convert it to a JavaScript object via standard JSON.parse() or jQuery's $.parseJSON .

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';

$.each(JSON.parse(json), function(idx, obj) {
alert(obj.tagName);
});

//or 

$.each($.parseJSON(json), function(idx, obj) {
alert(obj.tagName);
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn