*******
* *
* * *
* *
*******
它应该看起来像上面的星号排列。我是编程新手。到目前为止,我写了:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<script>
var maxCount = 7;
var iterationCount = 0;
while (iterationCount < maxCount) {
iterationCount = iterationCount + 1;
document.write('*');
}
到目前为止,我有一种强烈的感觉,这是不正确的,即使它是正确的,我也不知道该怎么做。 我知道我必须使用for和嵌套循环,但我非常困惑。
答案 0 :(得分:0)
尝试
var width = 7,
height = 7, // for example
boxElem = document.getElementById("box"); // this is the element which will hold your box
for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
if(i === 0 || i === height - 1 || j === 0 || j === width - 1 || (i === Math.floor(height / 2) && j === Math.floor(width / 2))) {
// check if it's the first or last row or column, or if it's the centre of the box
boxElem.innerHTML += "*";
} else {
boxElem.innerHTML += " "; // otherwise, don't add an asterisk but an empty space
}
}
boxElem.innerHTML += "\n"; // new line
}