Given a number
n
and a characterc
, the task is to replace the innerHTML of an element withn
rows of text. The first row should have one copy ofc
, the second row should have two copies ofc
, etc.<br>
tags are to be inserted to separate each row.
我一直认为嵌套 for
循环在这里可能是合适的,其中外部 for
创建行,以及内部 for
重复每一行中的字符,但就是无法在我的脑海中将它们放在一起,并且不确定这是否是一个好的方法。
我在想也许是这样的:
for(i = 1; i <= n; i++) {
for(j = 1, j <= n; j++) {
document.getElementById("output").innerHTML = c;
}
document.getElementById("output").innerHTML += <br>;
}
最佳答案
嵌套 for
循环通常会对性能产生不良影响,但假设您正在小规模地执行此操作,这应该会让您了解要做什么 http://jsfiddle.net/mrodkc1u/1/
但是,由于行数与最大行中的字符数相同,因此您不需要使用嵌套循环。这是一个更新的 fiddle ,只有一个循环 http://jsfiddle.net/mrodkc1u/2/
关于javascript - 使用 JavaScript 在第 n 行插入 n 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818595/