我的程序应该从第一段中获取文本,将其复制 100 次,然后将其放入第二段中。但是当我执行此功能时:
<html>
<body>
<p id="first">First</p>
<p id="second">Second</p>
<script>
var i;
var word = document.getElementsByTagName('p')[0].innerHTML;
document.writeln(word); //Did this to check if it copied "first" correctly.
for (i=0; i<100; i++){
word+=word;
document.write(i) //Did this to see how man time it loops
}
document.getElementById("second").innerHTML = word;
</script>
</body>
</html>
它在 Safari 中返回这个(仅循环 27 次):
First
Second
First 0123456789101112131415161718192021222324252627
并在 Chrome 中返回此值(仅循环 24 次):
First
Second
First 0123456789101112131415161718192021222324
谢谢!
最佳答案
你的程序现在正在尝试做什么以使第二段包含 2^100 次“First”,因为你复制了重复项,在第一个循环之后你有 2*“First”,然后是 4*“First”等.这显然会带来内存问题。如果您想让第二段仅包含 100 次“First”,您可以使用:
<script>
document.getElementById("second").innerHTML =
document.getElementById("first").innerHTML.repeat(100)
</script>
关于JavaScript 未完成循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066748/