中断javascript循环

Break javascript loop

本文关键字:循环 javascript 中断      更新时间:2023-09-26

我有以下代码来使用谷歌图像搜索API:

google.load('search', '1');   
    function searchComplete(searcher) {
      // Check that we got results
      if (searcher.results && searcher.results.length > 0) {
        // Grab our content div, clear it.
        var contentDiv = document.getElementById('contentimg');
        contentDiv.innerHTML = '';
        // Loop through our results, printing them to the page.
        var results = searcher.results;
        for (var i = 1; i < results.length; i++) {
          // For each result write it's title and image to the screen
          var result = results[i];
          var imgContainer = document.createElement('div');

          var newImg = document.createElement('img');
          // There is also a result.url property which has the escaped version
          newImg.src = result.tbUrl;

          imgContainer.appendChild(newImg);
          // Put our title + image in the content
          contentDiv.appendChild(imgContainer);

问题是,它给了我3个图像结果。如何打破一个循环,只显示第一个而不是3个图像?如果我将for (var i = 1; i < results.length; i++)更改为for (var i = 3; i < results.length; i++),它只显示一个图像,但显示的图像是第三个,我需要显示第一个:)请告知

根本不要使用for循环。只需将i的所有实例替换为0。

google.load('search', '1');   
    function searchComplete(searcher) {
      // Check that we got results
      if (searcher.results && searcher.results.length > 0) {
        // Grab our content div, clear it.
        var contentDiv = document.getElementById('contentimg');
        contentDiv.innerHTML = '';
        var result = searcher.results[0];
        var imgContainer = document.createElement('div');
        var newImg = document.createElement('img');
        // There is also a result.url property which has the escaped version
        newImg.src = result.tbUrl;
        imgContainer.appendChild(newImg);
        // Put our title + image in the content
        contentDiv.appendChild(imgContainer);

0表示返回的第一个项(编程中几乎所有的数字序列都从0开始!),因此所有其他结果都将被忽略。

当您只想要一个元素时,不需要for循环。您可以使用访问数组的第一个元素

result = results[0];

数组是从零开始的。因此,当它包含三个图像时,这些图像被命名为results[0]、results[1]和results[2]。

使用break statement。一旦找到图像,它将终止循环,因此您将只有第一个图像。

      for (var i = 1; i < results.length; i++) {
      // For each result write it's title and image to the screen
      var result = results[i];
      var imgContainer = document.createElement('div');

      var newImg = document.createElement('img');
      // There is also a result.url property which has the escaped version
      newImg.src = result.tbUrl;

      imgContainer.appendChild(newImg);
      // Put our title + image in the content
      contentDiv.appendChild(imgContainer);
       //Berore the end of the loop
      if(i==1)
      {
      break;
      }
   }