简体   繁体   中英

random number generation and nested array in JavaScript

I am trying to generate random number for creating scatter plot with d3js. I am doing it in the following manner:

 //declare an array of arrays var dataset = [ [] ]; var inner = []; /* set the svg width and height */ var svgWidth = 500; var svgHeight = 100; var xCoord = 0; var yCoord = 0; for (var i = 0; i < 20; i++) { do { xCoord = Math.floor(Math.random() * svgWidth); yCoord = Math.floor(Math.random() * svgHeight); } while (xCoord <= 0 | yCoord <= 0); if (xCoord > 0 && yCoord > 0) { inner.push(xCoord); inner.push(yCoord); dataset.push(inner); } inner = []; } var svg = d3.select("body") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight); svg.selectAll("circle") .data(dataset) .enter() .append("circle") .attr("cx", function(d) { return d[0]; }) .attr("cy", function(d) { return d[1]; }) .attr("r", 5); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

The outer array should contain only 20 elements, I found out that it is creating 21 elements instead with the first element with only the radius values and no coordinate value for the center of the circle. Some hint would be great to have to understand the issue.

The inner array isn't necessary, in fact it's the problem.

var dataset = [
  []
];

Just remove it.

var dataset = [];

Try this:

//declare an array of arrays
var dataset = [];
var inner = [];

/*
    set the svg width and height
*/
var svgWidth = 500;
var svgHeight = 100;
var xCoord = 0;
var yCoord = 0;

for (var i = 0; i < 20; i++) {
  do {
    xCoord = Math.floor(Math.random() * svgWidth);
    yCoord = Math.floor(Math.random() * svgHeight);
  } while (xCoord <= 0 | yCoord <= 0);


  if (xCoord > 0 && yCoord > 0) {
    inner.push(xCoord);
    inner.push(yCoord);

    dataset.push(inner);
  }

  inner = [];
}

var svg = d3.select("body")
  .append("svg")
  .attr("width", svgWidth)
  .attr("height", svgHeight);


svg.selectAll("circle")
  .data(dataset)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return d[0];
  })
  .attr("cy", function(d) {
    return d[1];
  })
  .attr("r", 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM