简体   繁体   English

在JavaScript中访问嵌套数组项

[英]Access nested array items in javascript

I'm using the javascript trivia API to make an application. 我正在使用javascript trivia API制作应用程序。 I'm having issues displaying each of the values of the wrong answer. 我在显示错误答案的每个值时遇到问题。

So far I have saved them in my state, along with the questions, and the correct answer 到目前为止,我已经将它们以及问题和正确答案保存在我的状态中

componentDidMount() {
  axios.get('https://opentdb.com/api.php?amount=50').then(response => {
    for (var key in response.data.results) {
      console.log(response.data.results[key].question)
      this.setState(prevState => ({
        questions: [...prevState.questions, response.data.results[key].question],
        answers: [...prevState.answers, response.data.results[key].correct_answer],
        wrongAnswers: [...prevState.wrongAnswers, response.data.results[key].incorrect_answers]

      }));
    }
  });
}

this works fine, but my issue is that the wrong answers is an array itself, so whenever I display the state 这很好用,但是我的问题是错误的答案是数组本身,所以每当我显示状态时

<p>{this.state.wrongAnswers[this.state.random]}</p> // prints array of strings

I get another array, and I can access each element using the dot operator, because I don't know the answers since the questions are chosen randomly. 我得到另一个数组,我可以使用点运算符访问每个元素,因为由于问题是随机选择的,所以我不知道答案。

I want to display the values dynamically using radio buttons. 我想使用单选按钮动态显示值。 Is there a way to access each element of the nested array and display them dynamically? 有没有办法访问嵌套数组的每个元素并动态显示它们?

You can loop through that array and show the wrong answers 您可以遍历该数组并显示错误的答案

{Array.isArray(this.state.wrongAnswers) && this.state.wrongAnswers.map((wrongAnswer, index) => {
  <p key={'Key-'+index}>wrongAnswer}</p>
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM