【问题标题】:js for loop keeps looping unlimitedly [closed]js for循环不断循环无限[关闭]
【发布时间】:2020-04-26 00:02:24
【问题描述】:

我真的坚持这部分。首先,我成功收集了用户上传的summernote编辑器中的所有img源。但是当我尝试循环它们以检查 img 链接是否编码为 base64 并尝试解码它们并将它们保存在一起时。但是在我的代码中,fo循环一直在无限循环。 img标签的循环列表有问题吗?

function getAllImages() {
let images = $(".note-editable p").find('img').map(function() {
      return $(this).attr('src')
    }).get();
console.logt(images);
 let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
 let imgSrc = [];
   for(let i=0; images.length; i++){
     if(base64regex.test(images[i])) {
        console.log("["+images[i]+"]");
        let decoded=atob(images[i]);
        console.log("img decoded");
        imgSrc.push(decoded);
     } 
     else if(base64regex.test(images[i]) == false){

        console.log("["+images[i]+"]");
        imgSrc.push(images[i]);
     }      
 }
  return imgSrc;
 }

【问题讨论】:

  • for(let i=0; images.length; i++){ 应该是for(let i=0; i < images.length; i++){
  • for(let i=0; images.length; i++){ 你缺少一个终止条件,它应该是i < images.length
  • 啊,非常感谢,为此我花了一整天的时间。有趣的是为什么 js 在那里没有显示任何错误?
  • @AzizSirojiddinov - 因为没有错误。 for 循环中的测试表达式只是一个表达式。 images.length 是一个表达式。 :-) for 不要求表达式具体评估为 truefalse (这在某些情况下非常有用)。然后测试表达式的结果,看它是真的(= 循环应该继续)还是假的(它不应该)。如果images.length 是一个非 0 的数字,它是真实的,所以它会永远持续下去。

标签: javascript jquery for-loop summernote


【解决方案1】:

请在 for 循环中使用i < images.length

function getAllImages() {
let images = $(".note-editable p").find('img').map(function() {
      return $(this).attr('src')
    }).get();
console.logt(images);
 let base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
 let imgSrc = [];
   for(let i=0; i < images.length; i++){
     if(base64regex.test(images[i])) {
        console.log("["+images[i]+"]");
        let decoded=atob(images[i]);
        console.log("img decoded");
        imgSrc.push(decoded);
     } 
     else if(base64regex.test(images[i]) == false){

        console.log("["+images[i]+"]");
        imgSrc.push(images[i]);
     }      
 }
  return imgSrc;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多