循環對象,我有一些問題,我的JavaScript問題在javascript
<html>
<body>
<p id="demo2"></p>
<script>
var text = '{"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["ma0072c","blue",1.4],["joe","brown",1.7],["zehua","black",1.8]]}';
var obj = JSON.parse(text);
var x= Object.keys(obj.h).length;
var y= Object.keys(obj.d).length;
var json_datas = JSON.stringify(obj.h);
var json_data = JSON.stringify(obj.d);
var obj2 = JSON.parse(json_data);
var json_data2 = JSON.stringify(obj2[1]);
var obj3 = JSON.parse(json_data2);
var newjson = [];
var newjson2 = [];
i=0;
l=0;
z=0;
m=0;
var boys= {};
for (i in obj.h){
boys[obj.h[i]] = obj.d[m][l];
l++;
z++;
m++;
newjson.push(boys);
}
newjson2 = newjson2.concat(newjson);
var newjson2 = JSON.stringify(newjson);
document.getElementById("demo2").innerHTML = newjson2;
</script>
</body>
</html>
這個腳本boys[obj.h[i]] = obj.d[m][l];
爲什麼代碼不希望循環?有人能告訴我正確的循環嗎?我想這樣的
[{"username":"ali","hair_color":"brown","height":1.2},
{"username":"marc","hair_color":"blue","height":1.4},
{"username":"joe","hair_color":"brown","height":1.7},
{"username":"zehua","hair_color":"black","height":1.8}]
但我輸出的輸出,現在就是這個樣子
[{"username":"ali","hair_color":"brown","height":1.2},
{"username":"ali","hair_color":"brown","height":1.2},
{"username":"ali","hair_color":"brown","height":1.2},
{"username":"ali","hair_color":"brown","height":1.2}]
@nishant,well spotted – Billy
並且不要在數組中使用'for ...in'循環 – adeneo
@Nishant在'for-in'循環中不需要'i ++' –