在JavaScript中显示一个迭代阵列的单个元素



我正在获得此json的值电影",使用阵列的索引[]它向我展示了一个元素,尽管以同样的方式,JavaScript在其余元素中都在迭代。

我怀疑有必要调用get((函数以获取每个值。

我仍然专注于您的评论,大师。

我的代码:

window.onload = function () {
  function get(URL, callback) {
    const typeRequest = new XMLHttpRequest();
  
    typeRequest.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        callback(null, JSON.parse(this.responseText));
      } else {
        callback(new Error(`Se produjo un error al realizar el request ${this.status}`));
      }
    }
    
    typeRequest.open("GET", URL);
    typeRequest.send(null);
  }
  
  function _handleError (err) {
    console.log(`Request failed ${err}`);
  }
  
  get('https://swapi.co/api/people/1', function (err, luke) {
    if (err) return _handleError;
    get(luke.homeworld, function (err, homeworld) {
      if (err) return _handleError;
      for(let p = 0; p < luke.films.length; p++) {
          get(luke.films[0], function (err, films) {
            if (err) return _handleError;
            console.log(films.title);
          })
      }
      luke.homeworld = homeworld;
      console.log(`Además, ${luke.name.substr(0, 4)} nació en el planeta ${luke.homeworld.name}`);
    })
    console.log(`Request succeded`);
    console.log(`Working by: ${luke.name}
    Height: ${luke.height}
    Peso: ${luke.mass}
    Color de cabello: ${luke.hair_color}
    Color de ojos: ${luke.eye_color}`);
  });
}

删除for-loop,只需检查属性length

if (luke.films.length) {
    get(luke.films[0], function (err, films) {
        if (err) return _handleError;
        console.log(films.title);
    })
}

window.onload = function () {
  function get(URL, callback) {
    const typeRequest = new XMLHttpRequest();
  
    typeRequest.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        callback(null, JSON.parse(this.responseText));
      } else {
        callback(new Error(`Se produjo un error al realizar el request ${this.status}`));
      }
    }
    
    typeRequest.open("GET", URL);
    typeRequest.send(null);
  }
  
  function _handleError (err) {
    console.log(`Request failed ${err}`);
  }
  
  get('https://swapi.co/api/people/1', function (err, luke) {
    if (err) return _handleError;
    get(luke.homeworld, function (err, homeworld) {
      if (err) return _handleError;
      if (luke.films.length) {
        get(luke.films[0], function (err, films) {
            if (err) return _handleError;
            console.log(films.title);
          })
      }
      luke.homeworld = homeworld;
      console.log(`Además, ${luke.name.substr(0, 4)} nació en el planeta ${luke.homeworld.name}`);
    })
    console.log(`Request succeded`);
    console.log(`Working by: ${luke.name}
    Height: ${luke.height}
    Peso: ${luke.mass}
    Color de cabello: ${luke.hair_color}
    Color de ojos: ${luke.eye_color}`);
  });
}

最新更新