如何停止两次打印循环的输出 [英] How can I stop the output of a loop being printed twice

查看:99
本文介绍了如何停止两次打印循环的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个程序,列出太空人的名单。







这就是我想要的输出:



name1 name2 name3



但结果如下:



name1 name2 name3 name1 name2 name3



我该怎么办?

谢谢



我的尝试:



I want to make a program that gives a list of the people in space.



This is what i want the output to be like:

name1 name2 name3

but this is the result:

name1 name2 name3 name1 name2 name3

What do i do?
thanks

What I have tried:

<div id="space_astronauts">
    <span id="child_1"></span>
</div>




var space = new XMLHttpRequest();
space.open("GET", "http://api.open-notify.org/astros.json", "jsonp");
space.send(null);
space.onreadystatechange = function() {
	var res = JSON.parse(space.response);
	
	var totalPeople = res.number;
	for (i = 0; i < totalPeople; i++) {
		var pElement = document.getElementById("space_astronauts");
		var firstChild = pElement.firstChild;
		var astronautsElement = document.createElement("a");
   		var txt = document.createTextNode(res.people[i].name + " ");
   		astronautsElement.appendChild(txt);

   		pElement.insertBefore(astronautsElement, firstChild);
   	}
}

推荐答案

if(this.readyState == 4& & this.status == 200){

响应中缺少上述条件,导致数据打印两次。



if (this.readyState == 4 && this.status == 200) {
the above condition is missing in the response, which leads to print the data twice.

var space = new XMLHttpRequest();
       space.open("GET", "http://api.open-notify.org/astros.json", "jsonp");
       space.send(null);
       space.onreadystatechange = function () {
           if (this.readyState == 4 && this.status == 200) {
               var res = JSON.parse(space.response);

               var totalPeople = res.number;
               for (i = 0; i < totalPeople; i++) {
                   var pElement = document.getElementById("space_astronauts");
                   var firstChild = pElement.firstChild;
                   var astronautsElement = document.createElement("a");
                   var txt = document.createTextNode(res.people[i].name + " ");
                   astronautsElement.appendChild(txt);

                   pElement.insertBefore(astronautsElement, firstChild);
               }
           }
       }


这篇关于如何停止两次打印循环的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆