在数组中添加项并检索它们失败

Adding items in array and retrieving them fails to work

本文关键字:检索 失败 数组 添加      更新时间:2023-09-26

我想用HTML和CSS制作一个有6个框的猜谜游戏,然后给每个框一个唯一的颜色。

我用RGB生成颜色,但它没有形成数组,数组只有1,2,3,4,5,6。

var colors = [];
var squares = document.querySelectorAll(".square");
function generateColors (num){
  var r = Math.floor(Math.random()* 256);
  var g = Math.floor(Math.random()* 256);
  var b = Math.floor(Math.random()* 256);
  var rgb = "rgb(" + r + ", " + g + ", " + g + ")";
  var i = 0;
  for(i; i <= num-1; i++){
    colors[i] = colors.push(rgb);
  }
  for(i; i <= num-1; i++){
    squares[i].style.background = colors[i];
  }
  console.log(rgb);
}
generateColors(6);

您只定义每个变量(r、g和b(一次,这样它们就不会是6种不同的颜色。你还把颜色看成一根绳子。这对你来说是非常好的阅读,但css不会得到这个。改为使用rgb((函数,如下所示:squares[i].style.background.rgb(r,g,b);

您的代码中几乎没有错误。

首先,使用colors.push(rgb)代替colors[i] = colors.push(rgb)

其次,在for循环的每次迭代中都必须丢失新颜色,这就是为什么必须在循环中放入Math.random操作的原因。否则,每次都会丢失相同的rgb。

var colors = [];
var squares = document.querySelectorAll(".square");
function generateColors(num) {
  for (var i = 0; i < num; i++) {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
    colors.push(rgb);
  }
  for (var i = 0; i < num; i++) {
    squares[i].style.background = colors[i];
  }
}

rgb的值应该在用于加载颜色的循环内。

    var colors = [];
    var squares = document.querySelectorAll(".square");
    function generateColors(num) {
      var i = 0;
      for (i; i <= num - 1; i++) {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
        colors.push(rgb);
      }
      for (i; i <= num - 1; i++) {
        squares[i].style.background = colors[i];
      }
      console.log(colors);
    }
    generateColors(6);

一些事情。尽可能优化cicles。您生成的值在cicle之外,因此它们只被调用一次。在rgb中打印"蓝色"部分时出现了一个小错误。

var colors;
var squares;
function generateColors(num){
  squares = document.querySelectorAll('.square');
  colors = [];
  var r,g,b, rgb;
  for(var i = 0; i < num; i++){
    r = Math.floor(Math.random()* 256);
    g = Math.floor(Math.random()* 256);
    b = Math.floor(Math.random()* 256);
    rgb = "rgb(" + r + ", " + g + ", " + b + ")";
    colors.push(rgb);
    squares[i].style.background = rgb;
  }
}
body{
  display:flex;  
}
.square{
  width:20px;
  height:20px;
  background:#aaa;
  border: 1px solid black;
  padding:5px;
}
<div class="square">
A
</div>
<div class="square">
B
</div>
<div class="square">
C
</div>
<div class="square">
D
</div>
<div class="square">
E
</div>
<div class="square">
F
</div>
<button onclick="generateColors(6)">Generate</button>