最近的项目需要模拟一个json格式的数据,
格式如下
{
"studentA": [
{
"grade": "A",
"class": "B",
"course": {
"a": "0-100",
" b ": "0-100"
}
}
],
"studentB": [
{
"grade": "A",
"class": "B",
"course": {
"a": "0-100",
" b ": "0-100"
}
}
]
}
我们要实现这个功能,
1、变量和数组声明
var score= new Array();
var num1=d3.range(6).map(d3.random.normal(0.8,0.1));
// 随机生成年级
var grades=[1,2,3,4];
// 随机生成班级
var classes=[1,2];
//随机生成姓
var lastnames=["赵","钱","孙","李","周","吴","郑","王","冯","陈","卫","蒋","沈","韩","杨","朱","秦","许","何","吕","施","张"];
//随机生成名
var firstnames=["伟","芳","娜","丽","强","静","敏","磊","军","涛","明","刚","洁","斓","文","华","金","斌","波","辉","亮","超"];
2、构造函数
function getStu(){
var stu = {
"name":"",
"detail":{}
};
var lastname=lastnames[Math.floor(Math.random()*lastnames.length+1)-1];
var firstname=firstnames[Math.floor(Math.random()*firstnames.length+1)-1];
var grade=Math.floor(Math.random()*4+1);
var classe=Math.floor(Math.random()*2+1);
stu.name = lastname+firstname;
stu.detail.grade = grade;
stu.detail.class = classe;
stu.detail.score = num1.map(function(d){
return d*100>100?100:Math.round(d*100);
});
return stu;
}
下面我们用innerHTML给页面中写入内容:
temp.innerHTML='
<div id="copy">
{<br>
<span>
"<label></label>":[
<br> {
<br>
"grade":"<label></label>",<br>
"class":"<label></label>",<br>
"course":{<br>
"计算机网络":"<label></label>",<br>
"大学英语":"<label></label>",<br>
"Web前端开发":"<label></label>",<br>
"C语言程序设计":"<label></label>",<br>
"数据结构":"<label></label>",<br>
"大学物理":"<label></label>",<br>
}
<br>
}<br>
],<br>
</span>}
</div>';
temp.getElementsByTagName("label")[0].innerHTML=stu.name;
temp.getElementsByTagName("label")[1].innerHTML=stu.detail.grade;
temp.getElementsByTagName("label")[2].innerHTML=stu.detail.class;
temp.getElementsByTagName("label")[3].innerHTML=stu.detail.score[0];
temp.getElementsByTagName("label")[4].innerHTML=stu.detail.score[1];
temp.getElementsByTagName("label")[5].innerHTML=stu.detail.score[2];
temp.getElementsByTagName("label")[6].innerHTML=stu.detail.score[3];
temp.getElementsByTagName("label")[7].innerHTML=stu.detail.score[4];
temp.getElementsByTagName("label")[8].innerHTML=stu.detail.score[5];
document.getElementById("main").appendChild(temp);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。