Home > Software engineering >  Passing i of a for loop to another function?
Passing i of a for loop to another function?

Time:11-23

Current bootcamp student here. the element I'm innerTextingIs there a way to pass the index of a for loop to another function? I am trying to fetch an api (which gives me a random cryptocurrency of an array) 4 times, then pass that data to another function which allows me to innerText the info to the html. Please let me know if I can add anymore info or clarify. Thanks in advance.

<div >
        <div >
          <div >
            <div>
              <span >  $726 (15%)</span><br />
              <span >0.382 coin</span>
            </div>
          </div>
          <div>
            <h3  id="coin1name">BTC</h3>
            <h1  id="coin1price">Coin 1</h1>
          </div>
        </div>
        <div >
          <div >           
            <div>
              <span >  $726 (15%)</span><br />
              <span >0.382 coin</span>
            </div>
          </div>
          <div>
            <h3  id="coin2name">BTC</h3>
            <h1  id="coin2price">Coin 2</h1>
          </div>
        </div>
      </div>

function getRandomApi() {
  let randomApiUrl = `https://min-api.cryptocompare.com/data/blockchain/list?api_key=850252ca876085a93a414bceb298e21862313b438417b87364eb0fe9aab45e1c`;
  for (let i=1; i<5; i  ) {
  fetch(randomApiUrl)
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      console.log(data);
      updatePrice(data);
    });
  }
}

let updatePrice = function (randomData) {
  let keys = Object.keys(randomData.Data);
  console.log(Math.floor(Math.random() * keys.length));
  let propertyName = keys[Math.floor(Math.random() * keys.length)];
  console.log(propertyName);
  let symbolName = randomData.Data[propertyName].symbol;
  console.log(symbolName);
  fetch(
    `https://min-api.cryptocompare.com/data/price?fsym=${symbolName}&tsyms=USD`
  )
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      console.log(data);
      document.querySelector("#coin"   i   "price").innerText = `$${data.USD}`;
      document.querySelector("#coin"   "name").innerText = symbolName;
    });
};

CodePudding user response:

To pass i into your updatePrice function:

  • Modify the call from updatePrice(data); to updatePrice(data, i);
  • Define the function with multiple parameters, like so: function (randomData, i) {
  • Related