代码之家  ›  专栏  ›  技术社区  ›  James

对于p5内的循环。js和访问阵列[关闭]

  •  -8
  • James  · 技术社区  · 7 年前

    我有以下代码

    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 回复  |  直到 7 年前
        1
  •  -1
  •   Noah    7 年前

    下面是一个解释:

    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 作用

    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)
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.min.js"></script>

    这样,它只在以下情况下运行 设置 实际上是在运行。