Endless loop : why endless?

后端 未结 1 332
名媛妹妹
名媛妹妹 2021-01-25 18:01

Trying to find a way to remove blank pages from a document I wrote this script that does the job pretty well :

function remove_blank() {
var Doc = DocumentApp.op         


        
1条回答
  •  一向
    一向 (楼主)
    2021-01-25 18:27

    If I understand correctly, dd is essentially the 'current document element' that you're looking at. Look at the block of code below: (from your original post)

    if( type == DocumentApp.ElementType.PARAGRAPH ){
          tt=element.getText();
          if(tt!='  *  ') {
              element.removeFromParent();
              ++dd
          }
    }
    

    You only increment dd when a) It's a table. b) It's a paragraph with no text.

    You don't increment dd when it's a paragraph with text. So, when it hits a paragraph that HAS text, dd doesn't increment, so it checks the same paragraph again the next run through the loop. Thus leaving dd the same.

    There's one reason that I'm unsure about my answer. You stated that it runs fine the first time through. (I'm assuming the document has both empty and non-empty paragraphs). Supposedly, it should also get stuck in the first run once it hits a non-empty paragraph. I might just be missing something though.

    Regardless, I hope this answer will maybe help. If I notice anything else, I'll be sure to edit!

    Edit: I don't know if this applies, but if you have anything in your document that isn't a paragraph or table, it will also become stuck there.

    Edit#2: No problem, I completely understand what you're saying regarding the 500char limit and how hard it can be to describe certain things while abiding that :p. I just hope I interpreted your comment correctly.

    Regarding this code here:

    while(body.getNumChildren()>dd) {
    

    I believe that the while condition is re-evaluated each time that it is run. This means that body.getNumChildren() is called again, (sometimes) returning a smaller number because an element has been removed.

    I'm not 100% sure about how the system works either, but I believe that for example you have a list, [1] [2] [3]. If you remove [2] I suspect the list will do something like this... [1] [3] -> [1] [2] (where [3] becomes element [2]). As I said, I am not 100% sure about that, but if that is the case, maybe keeping dd constant when you remove an element might do the trick.

    0 讨论(0)
提交回复
热议问题