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

JQuery $.each遍历JavaScript数组对象实例_jquery

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

查看一个简单的jQuery的例子来遍历一个JavaScript数组对象。

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

上面的代码片断工作正常,提示 “apple”, “orange” … 等,如预期一样。
问题: JSON 字符串

下面的例子中,声明了一个JSON字符串(随附单或双引号)直接地。

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

在Chrome中,它显示在控制台下面的错误:

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

解决方案:JSON字符串转换为JavaScript对象。
要修复它,通过标准JSON.parse()或jQuery 的 $.parseJSON 将其转换为JavaScript对象。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!