Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

js生成随机数据

初涉 Js,想生成一组随机数据,基本的数据格式如下:

 var test_data = {
    "data": [{
        "seq": 36687,
        "vol": [63.27994918823242, 63.282066345214844, 63.28112030029297, 63.27827453613281, 63.27593231201172],
        "time": "2012-07-18-21-42-13-034",
        "hrate": 0,
        "status": 0
    },{
        "seq": 36688,
        "vol": [63.24958038330078, 63.249080657958984, 63.25041580200195, 63.25270080566406, 63.254817962646484],
        "time": "2012-07-18-21-42-13-072",
        "hrate": 0,
        "status": 0
    }],
}; 

问题: 我想随机生成 test_data,大概10万行, 纯js代码, seq是自增1,vol为5个随机数字,hrate和status均为0不变,time则是最后3个数字随机变化 (例子中为 42-13-034随机变化)

谢谢!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<script>
 var test_data = { data: [] };
 var data = test_data.data;
 for(var i = 36687; i < 36687 + 100000; i++){
    var temp = {
        seq: i,
        vol: getVol(),
        time: "2012-07-18-21-42-13-0" + getNum(),
        hrate: 0,
        status: 0
    }
    data.push(temp)
 }
 function getNum(){
  var num = parseInt(Math.random()*100)
  if(num < 10){
    num = "0" + num;
  }
  return num.toString();
 }
 function getVol(){
   var arr = [], i = 0;
   while(i < 5){
    arr.push(Math.random()*100);
    i++;
   }
   return arr;
 }
</script>

循环即可.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...