JavaScript:我如何制作一个Var"数组"工作?

时间:2017-11-14 20:57:07

标签: javascript arrays var

有没有办法用一种"数组命名一个var?"我的代码是这样的:

for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    var Square[i] = document.createElement("div");
    Square[i].style.position = "relative";
    Square[i].style.float = "left";
    Square[i].style.width = "50px";
    Square[i].style.height = "50px";
    Square[i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square[i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square[i]);
}

我知道我的代码不起作用,但我想实现相同的想法,所以我可以得到这样的结果:

var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc

我也试过做"Concentration" var,但它没有用。我该怎么做才能使文档多次附加相同的方格?

2 个答案:

答案 0 :(得分:1)

您的声明语法无效。但是,我认为您要尝试的更大一点是能够使用动态创建的元素填充数组,并且您可以这样做:

var squares = [];  // Array must exist before you can populate it

var testColorArray = ["green", "yellow", "blue", "orange", "silver"];
var getTestColor = null;

function makeSquares(count){

  for(var i = 0; i < count; i++){
    // Just create the element and configure it. No need to worry about the array yet
    var element = document.createElement("div");
    element.style.float = "left";
    element.style.width = "75px";
    element.style.height = "75px";
    element.id = "square" + (i + 1);
    element.style.backgroundColor = testColorArray[Math.floor(Math.random()* testColorArray.length)];
    element.textContent = element.id;
    squareCont.appendChild(element);
    
    // Now, add the element to the arrray
    squares.push(element);
  }
  
  // Test:
  console.log(squares);
}

makeSquares(10);
<div id="squareCont"></div>

答案 1 :(得分:1)

var Square = {};
var SquareCont = document.createElement('div');
var getHorizontalSquares = 10;
var getVerticalSquares = 10;
var TestColorArray = ['a','b','c','f','e','0','1','2','3','3','4','5'];
var getTestColor = '';
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    Square['Square'+i] = document.createElement("div");
    Square['Square'+i].style.position = "relative";
    Square['Square'+i].style.float = "left";
    Square['Square'+i].style.width = "50px";
    Square['Square'+i].style.height = "50px";
    Square['Square'+i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square['Square'+i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square['Square'+i]);
    getTestColor = '';
    
}
console.log(Square);

此示例使用对象而不是数组执行您想要的操作,但满足您动态创建可访问的Square1,Square2等的愿望......它们都包含在Square中。在具有此代码段的控制台中,您将看到创建了100个方块并将其添加到Square对象中。它们可以通过Square.SquareX(其中X是某个数字),或Square ['SquareX']或Square ['Square'+ X]访问,其中X是某个数字。