日期:2014-05-16  浏览次数:20338 次

【D3.V3.js系列教程】--(六)数据的威力

一、使用随机数值填充每一条

1、建立新的空的数据集数组

var dataset = [];                        //Initialize empty array
2、循环25次产生新的值
for (var i = 0; i < 25; i++) {           //Loop 25 times
3、产生0-30的随机数
    var newNumber = Math.random() * 30;  //New random number (0-30)
4、将数据加入数据集数组
    dataset.push(newNumber);             //Add new number to array
}

5、还可以产生整数

   var newNumber = Math.round(Math.random() * 30);
二、源码
<!DOCTYPE html>
<html>
  <head>
		<meta charset="utf-8">
		<title>testD3-5-dataPower.html</title>
		<script type="text/javascript" src="http://localhost:8080/spring/js/d3.v3.js"></script>
	<style type="text/css">
		
			div.bar {
				display: inline-block;
				width: 20px;
				height: 75px;	/* Gets overriden by D3-assigned height below */
				margin-right: 2px;
				background-color: teal;
			}
		
		</style>
	</head>
	<body>
		<script type="text/javascript">
		
			var dataset = [];  						 //Initialize empty array
			for (var i = 0; i < 25; i++) {			 //Loop 25 times
				var newNumber = Math.round(Math.random() * 30);  //New random integer (0-30)
				dataset = dataset.concat(newNumber); //Add new number to array
			}
			
			d3.select("body").selectAll("div")
				.data(dataset)
				.enter()
				.append("div")
				.attr("class", "bar")
				.style("height", function(d) {
					var barHeight = d * 5;
					return barHeight + "px";
				});
			
		</script>
	</body>
</html>

三、效果