如何使用for循环在数组中赋值?

时间:2016-01-28 05:00:29

标签: javascript html

我试图通过在javascript中使用for循环创建它来绘制一个tic tac toe board。但它根本没有绘制它。我知道这两个文件是链接的,因为我之前尝试过。但这不起作用。任何人都知道答案。

的Javascript

var array = [" "," "," "," "," "," "," "," "," "];
for(i = 0;i < 8;i++){
	array[i] = "| |";
	document.getElementById(board).innerHTMl = "|   |"];
}
<!DOCTYPE html>
<html> 
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div id="body">
<div><h1 id="middle">Tic Tac Toe</h1></div>
<p id="board"></p>
<script src="script.js"></script>

</div>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

假设您之前已经成功使用过此功能(如OP中所述,否则请分享一个小提琴),代码中有三个拼写错误

1)此行末尾有一个额外的方括号

document.getElementById(board).innerHTMl = "|   |"];
                                                  ^

应该是

 document.getElementById(board).innerHTMl = "|   |";

2)broad不是变量,它应该是字符串文字

document.getElementById('board').innerHTMl = "|   |";
                        ^     ^

3)innerHTMl应为innerHTML

document.getElementById('board').innerHTML = "|   |";
                                 --------^

答案 1 :(得分:-1)

var array = [" "," "," "," "," "," "," "," "," "];
for(i = 0;i < 8;i++){
	array[i] = "| |";
	$('#board').append("| | ");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html> 
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div id="body">
<div><h1 id="middle">Tic Tac Toe</h1></div>
<p id="board"></p>
<script src="script.js"></script>

</div>

</body>
</html>