Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to understand a code I found on the internet.

(我试图理解我在互联网上找到的代码。)

I dont't understand in the while loop, why it is not an infinite loop.

(我在while循环中不明白,为什么它不是无限循环。)

If change the calculator.appendChild in it to eg console.log it runs forever.

(如果改变calculator.appendChild在它如console.log它永远运行下去。)

 window.location.hash = 1;
 var calculator = document.createElement("div");
 calculator.id = "height-calculator";
 while (document.body.firstChild) {
    calculator.appendChild(document.body.firstChild);
 }
 document.body.appendChild(calculator);
 document.title = calculator.clientHeight;

Basically there is always a first child in a non-empty site, so the condition is always true.

(基本上,在非空站点中始终有第一个孩子,因此条件始终为真。)

Can someone explain why this way it doesn't run forever?

(有人可以解释为什么这种方式无法永远运行吗?)

  ask by B. Ma translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
444 views
Welcome To Ask or Share your Answers For Others

1 Answer

A element can only be child of one other element.

(A元素只能是一个其他元素的孩子。)

calculator.appendChild(document.body.firstChild);

As soon as you attach document.body.firstChild to your calculator, it automatically detaches from body, so body will eventually run out of children.

(将document.body.firstChild附加到计算器后,它会自动与主体分离 ,因此body最终将耗尽所有子代。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...