Я пытаюсь создать генератор цитат, и я пытаюсь взять цитаты из коллекции абзацев HTML.
Когда я пытаюсь получить доступ к случайному элементу списка узлов, я получаю все узлы в виде группы абзацев, а не только одного абзаца.
Это моя попытка рандомизатора:
const quotes = quotesdocument.querySelectorAll("p");
const randomize = function() {
for(quote of quotes) {
let num = (Math.floor(Math.random() * Math.floor(quotes.length)) - 1);
console.info(quotes.item(num));
}
}
А это отрывок из HTML, который я пытаюсь рандомизировать:
<p>“<a href = "https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.”</p>
<p>“Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.”</p>
<p>“We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for us.”</p>
<p>“Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.”</p>
<p>“Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.”</p>
Я ожидал, что получу только один из этих абзацев, но продолжаю получать их все.
Спасибо за помощь.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Причина, по которой он не работает, заключается в том, что вы повторяете все цитаты. Удаление цикла for и изменение логики рандомизации исправят это:
const quotes = document.querySelectorAll("p");
const randomize = function() {
let num = Math.floor(Math.random() * quotes.length) - 1;
console.info(quotes.item(num).innerText);
}
randomize();<p>“<a href = "https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.”</p>
<p>“Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.”</p>
<p>“We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for
us.”</p>
<p>“Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.”</p>
<p>“Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.”</p>В приведенном выше фрагменте я console.info() устанавливаю текст внутри элемента, чтобы вы могли видеть, что он работает, но для доступа к самому элементу просто удалите innerText, который я там разместил.
Цикл for..of, который есть в вашем коде, не нужен. Просто используйте код, который у вас уже есть, и num в качестве значения индекса массива quotes. Я добавил кнопку, чтобы продемонстрировать, как функция возвращает только одно значение:
function randomQuote() {
const quotes = document.querySelectorAll("p");
const num = (Math.floor(Math.random() * Math.floor(quotes.length)));
return quotes[num].innerText;
}
document.querySelector('#buttonEl').addEventListener('click', () => {
document.querySelector('#quoteEl').innerHTML = randomQuote();
});#quoteEl {
color: red;
}<input id = "buttonEl" type = "button" value = "Click for a random quote from the list below" />
<div id = "quoteEl"></div>
<p>“<a href = "https://theunboundedspirit.com/ananda-coomaraswamy-quotes/">Art</a> is the supreme task and the truly metaphysical activity in this life.”</p>
<p>“Underneath this reality in which we live and have our being, another and altogether different reality lies concealed.”</p>
<p>“We obtain the concept, as we do the form, by overlooking what is individual and actual; whereas nature is acquainted with no forms and no concepts, and likewise with no species, but only with an X which remains inaccessible and undefinable for
us.”
</p>
<p>“Everything which distinguishes man from the animals depends upon this ability to volatilize perceptual metaphors in a schema, and thus to dissolve an image into a concept.”</p>
<p>“Our destiny exercises its influence over us even when, as yet, we have not learned its nature: it is our future that lays down the law of our today.”</p>
Просто убрать шлейф
for? (и, вероятно,-1, иначе индекс иногда будет -1)