在数组中创建向量

Creating a vector in an array

我似乎无法在数组中嵌套向量。我使用了 createVector(),但发现它不起作用。我看了其他文章,虽然它们适用于非 p5 javascript,但这是我目前所在的位置:

function makePoints() {
    var cities = [];

    if (difficulty === 'hard') {
        cities.length = 40;

        for (i = 0; i < cities.length + 1; i++) {
            cities.push(new createVector(random(20, width - 20), random(20, height - 20)));
        }
    }
} 

为什么要改变cities.length?不仅如此:

var difficulty = 'hard';
function setup() {
  createCanvas(720, 400);
  makePoints();
}


function makePoints() {
  var cities = [],
      citiesSize = 40;

  if (difficulty === 'hard') {
    for (i = 0; i < citiesSize; i++) {
      cities.push(createVector(random(20, width - 20), random(20, height - 20)));
    }
  }
  console.log(cities);
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.min.js"></script>

您首先说的是 cities.length = 40,它用 40 undefined 填充数组。然后你在上面推动,但使用你要推动的数组作为停止的长度。所以第一次推使长度为 41,第二次推使长度为 42。你 运行 进入了一个无限循环,因为 i 永远不会达到 cities.length + 1(应该只是 cities.length)。

如果你想让你的数组长度为 40,那么不要推送,而是这样做:

for (i = 0; i < cities.length; i++) {
    cities[i] = createVector(random(20, width - 20), random(20, height - 20));
}