通过数组变量制作图案

时间:2018-09-22 19:34:41

标签: javascript

所以我有点理解我需要使用for循环,但是我完全陷入了困境。

有人可以告诉我我需要使用哪种类型的功能吗?

the basic should be like this, it won't be in terminal though, but normal javascript.

// Variables
var myarray     = [3, 4, 6, 6, 1, 3, 3];
var pOutput = document.getElementById("pOutput");
pOutput.innerHTML = 

//Events
for (var i = 0; i < myarray.length; i++){
pOutput.innerHTML += "="}
n
//Functions

3 个答案:

答案 0 :(得分:0)

您要执行的操作是在数组的每个值中打印等号乘以数字。为此,我建议您使用String原型中的repeat方法,如下所示:

// Variables
var myarray = [3, 4, 6, 6, 1, 3, 3];
var pOutput = document.getElementById("pOutput");

// Fixed this too
pOutput.innerHTML = "";

//Events
for (var i = 0; i < myarray.length; i++){
    pOutput.innerHTML += "=".repeat(myarray[i])
}

// ...

请确保下次再次提出更清晰的问题:)

答案 1 :(得分:0)

您可以使用嵌套循环将当前数组元素的值用作添加=的次数。

您也不会开始新行并先打印行号。

// Variables
var myarray = [3, 4, 6, 6, 1, 3, 3];
var pOutput = document.getElementById("pOutput");

var output = "";


for (var i = 0; i < myarray.length; i++) {
  output += `<br>${i} : `;
  for (var j = 0; j < myarray[i]; j++) {
    output += "=";
  }
}

pOutput.innerHTML = output;
<div id="pOutput"></div>

答案 2 :(得分:0)

您可以尝试这样的事情

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="output"></div>
    <script>
        const list = [3, 4, 6, 6, 1, 3, 3];
        const count = list.length;
        const result = [];
        const output = [];
        const dom = document.getElementById('output');

        for (let i = 0; i < count; i++) {
            const num = list[i];

            result[i] = [];

            for (let j = 0; j < num; j++) {
                result[i].push('=');
            }

            output[i] = `<div>${i} : ${result[i].join('')}</div>`;
        }

        dom.innerHTML = output.join('');
    </script>
</body>

相关问题