对于p5.js中的循环和访问数组

时间:2018-01-09 12:28:32

标签: javascript

我有以下代码

let position = []

function setup(){
let cnv = createCanvas(window.width,window.height);
  cnv.parent('canvas')
  noStroke()
  for(i = 0 ; i < 10 ;i++){
    let x = random(10,20)
    position.push(x)
  }
}
console.log(position[0])
function draw(){
  background('#fac81f')
  translate(width/2,height/2)
  ellipse(0,0,width/3)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.min.js"></script>

我希望能够访问数组中的对象,例如。

console.log(position[0])

位置[0]给我'未定义':(我很感激解释。非常感谢

1 个答案:

答案 0 :(得分:-1)

以下是解释:

let position = []

// This code only _declares a function called setup. It
// does not run the function.
function setup() {
  let cnv = createCanvas(window.width,window.height);
  cnv.parent('canvas')
  noStroke()
  for(i = 0 ; i < 10 ;i++){
    let x = random(10,20)
    position.push(x)
  }
}

// At this point, you have not added anything to
// position. It's a blank array, because `setup` has
// not been run.
console.log(position[0])

解决方案可能是将console.log放入setup函数。

&#13;
&#13;
let position = []

function setup() {
  for(i = 0 ; i < 10 ;i++){
    let x = random(10,20)
    position.push(x)
  }

  console.log(position[0])

  let cnv = createCanvas(window.width,window.height);
  cnv.parent('canvas')
  noStroke()
}

function draw(){
  background('#fac81f')
  translate(width/2,height/2)
  ellipse(0,0,width/3)
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.min.js"></script>
&#13;
&#13;
&#13;

这种方式只有在实际运行setup时才会运行。