javascript Firefox 在 for 循环中抛出 js 错误“分配大小溢出”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27645489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firefox throwing js error in for loop "allocation size overflow"
提问by Rajasekhar
Below is my code
下面是我的代码
Same code is working in local server but not in live.
相同的代码在本地服务器上工作,但不在现场。
htmlC = "";
htmlC += '<select name="pagenum" id="pagenum" style="width:135px" onChange="setPageSearchValue(this.value)">';
for(i=1 ; i<=tot_pages ; i++)
{
if(i.toString() == document.frmlist.start.value)
{
htmlC += "<option value='"+i+"' 'selected' >"+i+"</option>";
}
else
{
htmlC += "<option value='"+i+"'>"+i+"</option>";
}
}
htmlC += '</select>';
I have tried finding infinite loop but no success. Very same code is working in local server.
我试图找到无限循环但没有成功。非常相同的代码在本地服务器上工作。
回答by jishi
Using string concatenation in this manner is usually a bad idea, especially if you don't know the number of iterations you will be doing. Every time you concatenate a string, you will reallocate the memory needed to fit the new string and need to garbage collect the old one (which might not even be done during the loop for performance reasons)
以这种方式使用字符串连接通常是一个坏主意,特别是如果您不知道将要进行的迭代次数。每次连接字符串时,您都将重新分配适合新字符串所需的内存,并需要对旧字符串进行垃圾回收(出于性能原因,在循环期间甚至可能不会这样做)
var htmlBuffer = [];
htmlBuffer.push('<select name="pagenum" id="pagenum" style="width:135px" onChange="setPageSearchValue(this.value)">');
for(i=1 ; i<=tot_pages ; i++)
{
if(i.toString() == document.frmlist.start.value)
{
htmlBuffer.push("<option value='"+i+"' 'selected' >"+i+"</option>");
}
else
{
htmlBuffer.push("<option value='"+i+"'>"+i+"</option>");
}
}
htmlBuffer.push('</select>');
htmlC = htmlBuffer.join('\n');
The above will define an array, to which you push each "row" onto. It will dynamically allocate memory needed for the expanding data, and finally, you allocate 1 string for the total amount of data . This is much more efficient. I don't know if this is the actual problem in your case (since we don't know what tot_pages are), but it's never a bad idea to avoid string concatenations in loops anyway.
上面将定义一个数组,您将每个“行”推到该数组上。它将动态分配扩展数据所需的内存,最后,您为数据总量分配 1 个字符串。这样效率更高。我不知道这是否是您的实际问题(因为我们不知道 tot_pages 是什么),但无论如何避免循环中的字符串连接从来都不是一个坏主意。
回答by NVRM
Adding a note, this error is likely to be thrown when looping using a malformed do..whileinside another loop.
添加一个注释,在另一个循环中使用格式错误的do..while 进行循环时可能会抛出此错误。
For the record the following snippet can throw this error when removing i++, or a bad condition in the while.
为了记录,以下代码段在删除i++或while 中的不良条件时可能会引发此错误。
["h","e","l","l","o"].forEach(function(e){
var k = ["w","o","r","l","d"]
var i = 0
do
k[i] = e+k[i],i++
while (i < k.length)
console.log(k)
})