猿问

如何在 JS 中正确子集特定对象

我目前正在做一些练习,我想在此 api 上打印每部电影的标题:


https://jsonmock.hackerrank.com/api/movies?Year=1998


基本上,我希望每个标题都打印在第一页(或者最好是特定页面)。


这是我的代码:


<script>

function printTItles(year) {

  var res;

  

  xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {

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

      res = JSON.parse(this.responseText);

      

      for(var i=0;i<res.per_page;i++){

        document.getElementById("demo").innerHTML = res.data.i.Title;

      }

    };

  }

  xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=<year>", true);

  xmlhttp.send();

}

</script>

我知道问题出在res.data.i.title,但我不知道如何解决它。


白衣染霜花
浏览 104回答 1
1回答

12345678_0001

您正在尝试访问循环中索引处的元素i,就像访问对象的属性一样。i要获取数组中位置的元素res.data,您需要方括号访问[ ]此外,您不会将year请求中的参数替换为year传递给函数的参数。您可能想检查一下。这里我以年份2018为例。function printTItles(year) {&nbsp; var res;&nbsp;&nbsp;&nbsp; xmlhttp = new XMLHttpRequest();&nbsp; xmlhttp.onreadystatechange = function() {&nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; res = JSON.parse(this.responseText);&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; for(var i=0;i<res.per_page;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("demo").innerHTML = res.data[i].Title;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; }&nbsp; xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=2018", true);&nbsp; xmlhttp.send();}printTItles();<div id="demo"></div>您可以添加更多改进。例如,在每次迭代中,您都会替换#demo元素的内容。这会导致仅显示最后一个标题。相反,您可以将数据附加到 div 的现有 html 中。或者,就像我在本例中所做的那样,在将字符串设置为新值之前构建字符串innerHTML。function printTItles(year) {&nbsp; var res;&nbsp;&nbsp;&nbsp; xmlhttp = new XMLHttpRequest();&nbsp; xmlhttp.onreadystatechange = function() {&nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; res = JSON.parse(this.responseText);&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; var output = "";&nbsp; &nbsp; &nbsp; for(var i=0;i<res.per_page;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(res.data[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output += res.data[i].Title + '<br />';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("demo").innerHTML = output;&nbsp; &nbsp; };&nbsp; }&nbsp; xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=2018", true);&nbsp; xmlhttp.send();}printTItles();<div id="demo"></div>我还添加了一个条件来检查 处是否存在元素res.data[i]。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答