我正在尝试为我的类(class)编写一个程序,要求用户输入键盘字符,然后输入行数和列数,然后根据行和列以矩形显示该字符。
var keyBoardInput = prompt("Pick a key on your keyboard to display");
var x = prompt("How many rows?");
var y = prompt("How many columns?");
rectangleX = new Array(x);
rectangleY = new Array(y);
for(var i =0; i < rectangleX.lenght; i++)
{
rectangleX.push(keyBoardInput);
}
for(var j =0; j < rectangleY.lenght; j++)
{
rectangleY.push(keyBoardInput);
}
我不知道如何让它输出,所以说如果有 3 行和 2 列并且用户选择 a
作为键盘输入,我需要类似的输出:
aaa
aaa
最佳答案
这将是 2 行和 3 列,但如果它总是相同的字母,您可以创建一个双循环迭代您的行和列,并设置您想要输出的相应文本:
var x = 2
var y = 3
html = '';
for(var i =0; i < x; i++){ // for each row
for(var j =0; j < y; j++){ // we add a 'a' for each column in the row
html+= 'a'
}
// we already made a row, now we need a new line for the next row to show in the next line
html+='<br/>'
}
var newParagraph = document.createElement('p'); // we create a paragraph element
newParagraph.innerHTML = html; // set the html we made
document.body.appendChild(newParagraph); // and add it to the dom
通过 ecmascript6,我们可以使用利用字符串重复功能的单行解决方案:
html = ('a'.repeat(y)+'<br/>').repeat(x)
关于Javascript数组输入并显示用户定义的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33570842/