因此,作为将CSS,JS和HTML结合到一个交互式练习中的学习练习,我决定使用JS HTML和CSS在Web浏览器上重新创建2048游戏。我基本上在一个方形游戏板中编码了16个“盒子”元素。
我的问题主要与跨函数传递javascript数组有关。当我在cycleBoxes()中创建我的“boxes”数组时,长度应为16。但是,当我将空div元素推入“emptyBoxes”时,长度保持为1,然后返回到我当前不完整的generateNumber()函数。这可能是因为我的for循环只迭代一次。但是,我不明白为什么这是因为它应该在技术上迭代16次(console.log(boxes.length)返回16)没有?
以下是使用div容器构建类的示例:
<div id = "game_background">
<!-- Row 1 -->
<div id = "row_1" class = "row">
<div id = "1_1" class = "box">
<p class = "v"></p>
</div>
<div id = "1_2" class = "box">
<p class = "v"></p>
</div>
<div id = "1_3" class = "box">
<p class = "v"></p>
</div>
<div id = "1_4" class = "box">
<p class = "v"></p>
</div>
</div>
<!-- Row 2 -->
<div id = "row_2" class = "row">
<div id = "2_1" class = "box">
<p class = "v"></p>
</div>
<div id = "2_2" class = "box">
<p class = "v"></p>
</div>
<div id = "2_3" class = "box">
<p class = "v"></p>
</div>
<div id = "2_4" class = "box">
<p class = "v"></p>
</div>
</div>
这是我的JS
function generateNumber(){
var emptyBoxes = [];
emptyBoxes = cycleBoxes();
console.log(emptyBoxes.length);
//var random = Math.floor((Math.random()* (emptyBoxes.length+1) ));
}
function cycleBoxes(){
var boxes = document.getElementsByClassName("v");
console.log(boxes);
var emptyBoxes = [];
for(i = 0; i < boxes.length; i++){
if( boxes[i].innerHTML == ""){
emptyBoxes.push(boxes[i]);
}
return emptyBoxes;
}
答案 0 :(得分:3)
你忘记了for循环的结束括号:
for(i = 0; i < boxes.length; i++){
if( boxes[i].innerHTML == ""){
emptyBoxes.push(boxes[i]);
}
}
答案 1 :(得分:1)
以下代码是正确答案:
function cycleBoxes(){
var boxes = document.getElementsByClassName("v");
console.log(boxes);
var emptyBoxes = [];
for(i = 0; i < boxes.length; i++){
if( boxes[i].innerHTML == ""){
emptyBoxes.push(boxes[i]);
}
} // you forget this, without this, emptyBoxes will return with length 1
return emptyBoxes;
}