如何利用JavaScript遍历JSON数组

时间:2021-09-22 16:29:57

1、设计源码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>利用JavaScript遍历JSON数组</title>
<script type="text/javascript">
     function traJsonArray()
	 {
		 var jsonArray = [{"id":"100","name":"zhangsan","age":"23","sex":"man"},{"id":"101","name":"lisi","age":"21","sex":"woman"},{"id":"102","name":"wangwu","age":"22","sex":"man"}];
		 var inputText = "";
		 for(var json in jsonArray)
		 {
			 for(var key in jsonArray[json])
			 {
				inputText += jsonArray[json][key]+",";
			 }
		 }

		 document.getElementById("areaText").innerText = inputText;
	 }
</script>
</head>

<body>
   <div>
      <input type="button" id="btn" onclick="traJsonArray()" value="利用JavaScript遍历JSON数组"/>
      <textarea id="areaText" cols="80" rows="30"></textarea>
   </div>
</body>
</html>

2、设计结果

如何利用JavaScript遍历JSON数组