You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

P5.js排序算法可视化:数组条形无法绘制排查求助

问题分析与修复

你的代码没有绘制条形的核心原因是**generateBars函数逻辑错误,导致bars数组始终为空**,具体问题和修复方案如下:

1. 核心问题:初始化阶段bars数组未被填充

当第一次执行generateBars时,bars是空数组,内层的for (let j = 0; j < bars.length; j++)循环条件不成立(bars.length为0),循环体完全不会执行,也就不会触发bars[i] = new Bar(...)的赋值操作。后续循环中,只要bars没被填充,这个问题就会持续存在。

另外,你写的重复值判断逻辑也存在混乱:嵌套的双层循环判断x和height的唯一性,不仅效率低下,还会出现多次生成随机值却不完成赋值的情况。

2. 修复方案

方案一:简化逻辑,先填充再去重(更易维护)

如果需要生成x不重复、高度可重复的条形(排序可视化通常只需要x位置不重复,高度随机即可),可以先批量生成再处理重复值:

class Bar {
  constructor(x, height) {
    this.height = height;
    this.size = 10;
    this.x = x;
  }

  draw() {
    fill("blue");
    rect(this.x * this.size, height - (this.height * this.size), this.size, this.height * this.size);
  }
}

let bars = [];

function setup() {
  createCanvas(400, 400);
  generateBars();
}

function generateBars() {
  const usedX = new Set();
  // 生成39个不重复x的条形
  while (usedX.size < 39) {
    const randomX = floor(random(0, 39)); // 转为整数,避免浮点值导致的坐标误差
    if (!usedX.has(randomX)) {
      usedX.add(randomX);
      const randomHeight = floor(random(1, 40)); // 从1开始,避免高度为0的不可见条形
      bars.push(new Bar(randomX, randomHeight));
    }
  }
}

function draw() {
  background(220);
  bars.forEach(bar => bar.draw());
}

方案二:修复原逻辑的赋值问题(保留你的思路)

如果你坚持要在生成时即时判断重复,需要确保无论是否进入内层循环,都能完成赋值,同时修正判断逻辑:

function generateBars() {
  for (let i = 0; i < 39; i++) {
    let randomX, randomHeight;
    // 生成不重复的x
    do {
      randomX = floor(random(0, 39));
    } while (bars.some(bar => bar.x === randomX));
    
    // 生成不重复的height(如果需要的话)
    do {
      randomHeight = floor(random(1, 40));
    } while (bars.some(bar => bar.height === randomHeight));
    
    bars.push(new Bar(randomX, randomHeight));
  }
}

3. 额外优化点

  • 用floor()处理随机值:原代码中random(0,39)会生成浮点值,导致坐标出现非整数,可能影响绘制精度,转为整数更稳妥。
  • 避免高度为0:设置random(1,40)确保条形可见,不会出现高度为0的情况。
  • 用forEach替代普通for循环:代码更简洁易读。

内容的提问来源于stack exchange,提问作者Maddox Fox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:00:48