Home > Web Front-end > JS Tutorial > body text

JQuery $.each traverses JavaScript array object instances_jquery

WBOY
Release: 2016-05-16 16:38:20
Original
1263 people have browsed it

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);
});
Copy after login

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);
});
Copy after login

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);
});
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template