skip to Main Content

Im trying to make a simple webpage that shows random quotes. These are in Russian. I also want to show the translation in a separate box. The quotes are being picked at random. How do I link the index of the first array to the correct corresponding index position of the second array?

Please see my code. I’m new to coding so any advice is welcome.

let quotes = [
  "Вчера на вечеринке мы весело провели время", "Я начал здесь работать три года назад",
  "Вчера был худший день в моей жизни", "Когда-то у меня был щенок по кличке Шарик", "Все выходные шёл дождь", "Могли бы вы повторить это, пожалуйста?", "Как долго вы изучаете русский?",
  "На каком языке вы предпочитаете говорить?", "Можете посоветовать хорошую книгу на русском?"
]

let translation = ["Yesterday at the party , we had a great time.", "I started working here three years ago.", "Yesterday was the worst day of my life.",
  "I used to have a puppy named Sharik.", "It rained all weekend.", "Could you please repeat that?", "How long have you been studying Russian?",
  "In which language do you prefer to speak?", "Can you recommend a good book in Russian?"

]


function newQuote() {
  let randomNumber = Math.floor(Math.random() * (quotes.length));
  document.getElementById("quoteDisplay").innerHTML = quotes[randomNumber]

};
newQuote()
<div id="quoteDisplay""></div>

2

Answers


  1. Since the arrays are of the same length, use the same generated random index to get the corresponding English phrase:

    translation[randomNumber]
    
    Login or Signup to reply.
  2. Put your quotes and their translations in an array of ojects.

    let quotes = [
      {
        quote:"Вчера на вечеринке мы весело провели время",
        en:"Yesterday at the party , we had a great time."
      },
      {
        quote:"Я начал здесь работать три года назад",
        en:"I started working here three years ago."
      },
      {
        quote:"Вчера был худший день в моей жизни",
        en:"Yesterday was the worst day of my life."
      },
      {
        quote:"Когда-то у меня был щенок по кличке Шарик",
        en:"I used to have a puppy named Sharik."
      },
      {
        quote:"Все выходные шёл дождь",
        en:"It rained all weekend."
      },
    ]
    
    function newQuote(TranslateIn="en") {
      let randomNumber = Math.floor(Math.random() * (quotes.length));
      document.getElementById("quoteDisplay").innerHTML = quotes[randomNumber].quote;
      document.getElementById("quoteTranslationDisplay").innerHTML = quotes[randomNumber][TranslateIn];
    };
    newQuote();
    <h2>Quote</h2>
    <div id="quoteDisplay"></div>
    <h2>Translation(en)</h2>
    <div id="quoteTranslationDisplay"></div>
    <button onclick="javascript:newQuote();">New Quote</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search