Как отфильтровать массив для пользовательского ввода в js? - PullRequest
0 голосов
/ 20 ноября 2018

Я пытаюсь создать машину случайных кавычек, где пользователь может вставить слово темы, алгоритм ищет это слово в списке кавычек, создает новый список кавычек, содержащих это слово, а затем случайным образом возвращаетцитата из отфильтрованного списка.Если в списке нет слова, он возвращает любую случайную цитату.Я не могу понять, как сделать отфильтрованный список в JavaScript.Пока что у меня есть:

<body>
<p id="quoteDisplay"></p>
</body>
<form>
<input type="text" id="topic" />
<button onclick="wiseQuote()">Quote</button>
</form>

<script type="text/javascript">
var quotes = [
"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
"You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
"Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
"In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
"Everything in moderation, including moderation - Oscar Wilde",
"Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
"Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
"The truth is rarely pure and never simple. - Oscar Wilde",
"A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
"Perhaps one did not want to be loved so much as to be understood. - George Orwell",
"Facts do not cease to exist because they are ignored. - Aldous Huxley",
"Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
"A thing is not necessarily true because a man dies for it. - Oscar Wilde",
"The unexamined life is not worth living. - Socrates"
]

if (topic != null){
filteredQuotes = quotes.filter(function(){
return ;
});
}

if (filteredQuotes.length) {
randomIndex = Math.floor(Math.random() * filteredQuotes.length);
filteredQuote = filteredQuotes[randomIndex];
} else {
randomIndex = Math.floor(Math.random() * quotes.length);
filteredQuote = quotes[randomIndex];
}

document.getElementById('quoteDisplay').innerHTML = filteredQuote;
}

</script>

Это первый проект, который я создаю, поэтому я надеюсь, что этот код не слишком беспорядок !!Заранее всем большое спасибо :)

Ответы [ 2 ]

0 голосов
/ 20 ноября 2018

ниже - рабочий раствор;Тем не менее, я хочу обратиться к нескольким вещам с вашим исходным кодом, чтобы помочь вам.

  • Вы пришли из Java-фона или скопировали Java-решение откуда-то.У JavaScript нет size(), это length.Кроме того, вы не можете использовать int для принудительного ввода типа, так как Javascript - это язык со свободной типизацией.
  • Вы <p> находитесь внутри <body>, но ваш <form> находится вне<body>.Вы захотите убедиться и сохранить все, что вы хотите, чтобы пользователи видели внутри элемента * 1013.
  • Array.prototype.filter() ожидает, что вы вернете true или false, больше ничего не будет работать.
  • Ваша функция wiseQuote буквально закрывается перед запуском любого кода, вкладка кода поможет вам обнаружить подобные ошибки.
  • Я удалил элемент <form>, поскольку вы на самом деле не являетесьподавшее заявку.Это позволит вам не пытаться остановить обновление страницы с помощью e.preventDefault().

function wiseQuote(){
  var topic = document.getElementById("topic").value;
  var randomIndex;
  var filteredQuotes;
  var filteredQuote;
  
  if (topic != null){
    filteredQuotes = quotes.filter(function(quote){
      return quote.includes(topic);
    });
  }
  
  if (filteredQuotes.length) {
    randomIndex = Math.floor(Math.random() * filteredQuotes.length);
    filteredQuote = filteredQuotes[randomIndex];
  } else {
    randomIndex = Math.floor(Math.random() * quotes.length);
    filteredQuote = quotes[randomIndex];
  }
  
  document.getElementById('quoteDisplay').innerHTML = filteredQuote;
}

var quotes = [
    "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
    "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
    "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
    "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
    "Everything in moderation, including moderation - Oscar Wilde",
    "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
    "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
    "The truth is rarely pure and never simple. - Oscar Wilde",
    "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
    "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
    "Facts do not cease to exist because they are ignored. - Aldous Huxley",
    "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
    "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
    "The unexamined life is not worth living. - Socrates"
];
<input type="text" id="topic" />
<button onclick="wiseQuote()">Quote</button>
<p id="quoteDisplay"></p>
0 голосов
/ 20 ноября 2018

Вам необходимо получить значение на входе и в функции .filter() проверить, имеет ли пункт целевой текст или нет.Проверьте это, используя .indexOf().Затем сгенерируйте случайное число между 0 и длиной отфильтрованного массива и выберите один элемент из массива по индексу.

function wiseQuote(){
  // get value of input
  var topic = document.getElementById("topic").value;
  // filter array based of input value
  var filteredQuotes = quotes.filter(function(val) {
    return val.indexOf(topic) > -1;
  });
  // replace filtered array with origin array if it is empty
  filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
  // generate random number
  var rand = Math.floor(Math.random()*(filteredQuotes.length));
  // insert target item into html
  document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];  
}

function wiseQuote(){
  var topic = document.getElementById("topic").value;
  var filteredQuotes = quotes.filter(function(val) {
    return val.indexOf(topic) > -1;
  });
  filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
  var rand = Math.floor(Math.random()*(filteredQuotes.length));
  document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];  
}

var quotes = [
  "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
  "You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
  "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
  "In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
  "Everything in moderation, including moderation - Oscar Wilde",
  "Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
  "Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
  "The truth is rarely pure and never simple. - Oscar Wilde",
  "A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
  "Perhaps one did not want to be loved so much as to be understood. - George Orwell",
  "Facts do not cease to exist because they are ignored. - Aldous Huxley",
  "Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
  "A thing is not necessarily true because a man dies for it. - Oscar Wilde",
  "The unexamined life is not worth living. - Socrates"
];
<p id="quoteDisplay"></p>
<form>
  <input type="text" id="topic" />
  <button type="button" onclick="wiseQuote()">Quote</button>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...