我成功地能夠輸出for循環內最後隨機生成的點(randomX,randomY)的座標,但我似乎無法輸出所有這些將依賴於用戶需要多少。任何幫助,將不勝感激。謝謝。你可以在這裏看到現場項目http://math.mercyhurst.edu/~cmihna/DataViz/D3Chart.html輸出數組變量javascript
<!doctype html>
<html>
<head>
<script src="http://math.mercyhurst.edu/~lwilliams/js/d3.js"></script>
<style>
.axis path,
.axis line{
fill: none;
stroke: purple;
}
.axis text {
font-family: sans-serif;
font-size:10px;
}
</style>
</head>
<body>
<h1> D3 Scatter Plot</h1>
<script align='center' >
// create variables for the size of the SVG area that D3 will create
var w = 800
var h = 600
var pad = { left: 50, top: 50, bottom: 20, right: 20 }
var chartHeight = h - pad.top - pad.bottom
var chartWidth = w - pad.left - pad.right
var n = prompt("Enter the number of rolls")
for (var i = 0; i <n; i++)
{
var dataset = []
for (var i = 0; i < n; i++)
{
var randomX = Math.round(Math.random()*w)
var randomY = Math.round(Math.random()*h)
var randomR = Math.round(Math.random()*20)
dataset.push([randomX,randomY,randomR])
}
document.write(randomX + ' , ' + randomY)
console.log(dataset)
}
var xscale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[0] })])
.range([0,chartWidth])
var yscale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d[1] })])
.range([chartHeight,0])
var scatterSVG = d3.select("body")
.append('svg')
.attr('width', w)
.attr('height', h)
scatterSVG.selectAll('circle')
.data(dataset)
.enter()
.append('circle')
.attr('cx', function(d){ return xscale(d[0]) + pad.left })
.attr('cy', function(d){ return yscale(d[1]) + pad.top })
.attr('r', function(d){ return d[2] })
.attr('fill', function(d) {
return 'rgb(0,'+d[0]+','+d[1]+')'
})
var yAxis = d3.svg.axis()
.scale(yscale)
.orient('left')
.ticks(6)
var yAxisObject = scatterSVG.append('g')
.call(yAxis)
.attr("class", "axis")
.attr("transform", 'translate('+pad.left+','+pad.top+')')
var xAxis = d3.svg.axis()
.scale(xscale)
.orient('bottom')
.ticks(3)
var xAxisObject = scatterSVG.append('g')
.call(xAxis)
.attr("class","axis")
.attr("transform", 'translate('+pad.left+','+(h-pad.bottom)+')')
var out = "Here are the coordinates from your " + n + " rolls: ";
document.write(out)
</script>
</body>
<footer>
<br>
<br>
<br>
<br>
<input type="button" value="Enter New Number" onClick="window.location.href=window.location.href">
</footer>
</html>
嘗試在for循環中放置'document.write(randomX +','+ randomY)' – KiiroSora09
我已經試過了,它不起作用 – Thesystem32
然後請更新已經嘗試過的內容,以便我們不會猜測。 您是否嘗試過在for循環之外放置聲明'var dataset = []'並在最後(在'document.write(out)'之後循環它以輸出'dataset'數組的每個元素? – KiiroSora09