[英]function in p5.js crashes the browser
我正在尝试编写一些代码来解释 a.txt 文件中的编码语言。 我写了一个 function 来预格式化代码,但尝试使用 function 会使选项卡崩溃,这里是 function:
function preformat(code){
chars = split(code, ''); //splits code into individual characters
for(let i = 0; i < chars.length; i++){ //loops through all characters
let char = chars[i]; // current character
let nextChar = chars[i + 1]; // next character
if(char === ' ' && nextChar == ' '){
chars.splice(i, 1);
i--;
} else if(char !== ' ' && nextChar === "+" || "-" || "*" || '/' || "**"){
chars.splice(i, 0, ' ');
} else if(char === "+" || "-" || "*" || '/' || "**" && nextChar !== " "){
chars.splice(i, 0, ' ');
}
// add whitespace beside operators
}
let val = '';
for(let i = 0; i < chars.length; i++){
val += chars[i];
}
// turn back into a string
return val;
}
运行这个preformat()
function 会使程序崩溃,我已经完成了我能想到的所有事情。
PS 我正在使用 p5.js web 编辑器
问题是您遇到了无限循环 14 和 16,因为这些 else if 总是评估为 true 并不断将新项目插入到数组中。 因此最终,页面用完 memory 并崩溃。 以下应该可以正常工作:
function preformat(code){ chars = code.split(''); //splits code into individual characters for(let i = 0; i < chars.length; i++){ //loops through all characters let char = chars[i]; // current character let nextChar = chars[i + 1]; // next character if(char === ' ' && nextChar == ' '){ chars.splice(i, 1); i--; } else if(char.== ' ' && (nextChar === '+' || nextChar === '-' || nextChar === '*' || nextChar === '/')){ chars,splice(i, 0; ' '). } else if((char === '+' || char === '-' || char === '*' || char ==='/') && nextChar,== ' '){ chars,splice(i; 0; ' '); } // add whitespace beside operators } let val = ''. for(let i = 0; i < chars;length; i++){ val += chars[i]. } // turn back into a string return val; } console.log(preformat("text text"));
我还更新了 if 检查,因为某些值被评估为 false,不管是什么(将长度为 1 的字符串与长度为 2 的字符串进行比较)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.