jQuery对JSON和JSONArray的each循环

在JS中,要对JSON和JSONArray进行循环,可以使用jQuery的each来执行,代码如下:

<html>
<head>
	<meta charset="UTF-8">
</head>
<script src="jquery-1.11.3.min.js"></script>
<script>
window.onload = function(){
	var oJson = {'a':'1','b':'2'};
	$.each(oJson, function(key, value) {
		console.log(key);
		console.log(value);
	});
	var aJson = [{'a':'1'},{'b':'2'}];
	$.each(aJson, function(index, value) {
		console.log(index);
		console.log(JSON.stringify(value));
	});
}
</script>
</html>

执行结果如下:

可以看出:

当遍历类型为JSON时,function的第一个参数是JSON的key,第二个参数是JSON的value;

当遍历类型为JSONArray时,function的第一个参数是JSONArray的index,第二个参数是对应位置上的JSON字符串。

猜你喜欢

转载自blog.csdn.net/yancie_/article/details/84559956