我有一個 JavaScript 函式:
function addcontent(ele, text, lines, separate_lines){
if(separate_lines){
for(i=0; i<lines; i ){
text=text "\n" text "\n";
}
}
else if(!separate_lines){
for(e=0; e<lines; e ){
text=text text;
}
}
ele.append(text);
}
當我使用它來點擊 HTML 按鈕時,例如:
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
單擊按鈕時,我在 Chrome 控制臺中收到此錯誤:
未捕獲的 RangeError:HTMLButtonElement.onclick 處的 addcontent 處的字串長度無效
我不知道我錯在哪里,請幫忙。
提前致謝!
uj5u.com熱心網友回復:
問題是,在每次迭代中,您添加text兩次,但您text再次將結果分配給。
- 迭代 1:A A = AA(但您分配給
text)所以 - 迭代 2:AA AA = AAAA
- 迭代 3:AAAA AAAA = AAAAAAA
- 迭代 4:AAAAAAAA AAAAAAAA = AAAAAAAAAAAAAAAA
- 等等
所以它是指數的。您基本上是在進行 2行文本插入。您可以猜測這會創建一個“相當大”的字串并且無法處理。
對生成的文本使用不同的變數。
function addcontent(ele, text, lines, separate_lines) {
let finalText = text;
if (separate_lines) {
for (let i = 0; i < lines; i ) {
finalText = finalText "\n" text;
}
} else {
for (let e = 0; e < lines; e ) {
finalText = finalText text;
}
}
ele.append(finalText);
}
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
uj5u.com熱心網友回復:
這是古老的小麥和棋盤問題,繩子太長了。
您將字串加倍 100 次,即 2^100...
使用 say lines= 10可以正常作業
uj5u.com熱心網友回復:
如果您可以執行以下操作,則可以解決此問題:
text = (text "\n").repeat(lines * 2);
function addcontent(ele, text, lines, separate_lines) {
if (separate_lines) {
text = (text "\n").repeat(lines * 2);
} else if (!separate_lines) {
for (e = 0; e < lines; e ) {
text = text text;
}
}
ele.append(text);
}
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
如果你想在之后添加新行 A
function addcontent(ele, text, lines, separate_lines) {
if (separate_lines) {
text = `${text}<br>`.repeat(lines * 2);
} else if (!separate_lines) {
for (e = 0; e < lines; e ) {
text = text text;
}
}
ele.innerHTML = text;
}
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361877.html
標籤:javascript html 功能 for循环 字符串长度
上一篇:單擊復選框時更改svg形狀顏色
