亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法為數組中的變量賦值

無法為數組中的變量賦值

當年話下 2022-08-18 10:46:55
我正在用JavaScript創建一個簡單的項目,似乎無法弄清楚為什么這對我不起作用。我創建了一個函數,該函數獲取一個API以獲取隨機的國家/地區名稱,然后將該國家/地區名稱推入空數組,但我似乎無法弄清楚如何從該數組中為我的變量分配值,可能在這里缺少一些簡單的東西。getRandomWord();getRandomWord();getRandomWord();getRandomWord();const words = [];let selectedWord = words[Math.floor(Math.random() * words.length)];console.log(words);console.log(selectedWord);// Fetch some random wordsasync function getRandomWord() {  const res = await fetch('https://randomuser.me/api');  const data = await res.json();  const randomWord = data.results[0].location.country;  words.push(randomWord);}我需要從單詞數組中隨機分配一個國家/地區名稱到selectedWord,但它一直拋出未定義,盡管我在0到3的位置的單詞數組中看到4個不同的國家/地區名稱。有人可以向我解釋這一點,或者也許有更好的方法。謝謝!
查看完整描述

2 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

好的,所以我改變了一點代碼。


async function getRandomWord() {

  try {

    const res = await fetch('https://randomuser.me/api');

    const data = await res.json();


    const randomWord = data.results[0].location.country;


    return randomWord.toUpperCase();


    // words.push(randomWord.toUpperCase());

  } catch (e) {

    console.log(

      'There has been a problem with your fetch operation: ' + e.message

    );

  }

}

然后剛剛打電話給


(async () => {

  selectedWord = await getRandomWord();

  displayWord();

})();

不敢相信我做了這個:D謝謝。


查看完整回答
反對 回復 2022-08-18
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

讀取尚未解決,并且在執行時尚未填充。使用 Promise.all,然后:words[]selectedWords =


const p = Promise.all([

getRandomWord(),

getRandomWord(),

getRandomWord(),

getRandomWord()

]);


const words = [];


p.then(()=>{

const selectedWord = words[Math.floor(Math.random() * words.length)];


console.log(words);

console.log(selectedWord);

});


// Fetch some random words

async function getRandomWord() {

  const res = await fetch('https://randomuser.me/api');

  const data = await res.json();


  const randomWord = data.results[0].location.country;


  words.push(randomWord);

}


注意:如果您不希望快速失敗行為,則需要使用 Promise.allSettled,其中任何失敗都會導致它立即返回。另請注意,我正在使用Promise.all,以便它將同時運行提取,而不是按順序等待它們。


異步/等待而不是然后


(async()=>{

let words = [];


for(var i = 0; i < 4; i++)

  words.push(getRandomWord());

  

words = await Promise.all(words);


const selectedWord = words[Math.floor(Math.random() * words.length)];


console.log(words);

console.log(selectedWord);

})()


// Fetch some random words

async function getRandomWord() {

  const res = await fetch('https://randomuser.me/api');

  const data = await res.json();


  const randomWord = data.results[0].location.country;


  return randomWord;

}


查看完整回答
反對 回復 2022-08-18
  • 2 回答
  • 0 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號