如何为形成框的星号创建程序

How to create program for asterisks forming a box?

本文关键字:创建 程序      更新时间:2023-09-26
*******
*     *
*  *  *
*     *
*******

它应该看起来像上面的星号排列。我是编程新手。到目前为止,我已经写过:

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<script>
var maxCount = 7;
var iterationCount = 0;
while (iterationCount < maxCount) {
  iterationCount = iterationCount + 1;
  document.write('*');
}

到目前为止,我有一种强烈的感觉,这是不正确的,即使它是正确的,我也不知道如何从那里继续下去。我知道我必须使用 for 和嵌套循环,但我非常困惑。

尝试

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
}