如何使用Javascript从web抓取的多行文本中获得随机的单个结果



我有没有办法直接从行中获得随机的单个结果并输出它,而不必推送到healthArray

我的主要目标是提高性能,因为行最多可以是200多个文本,我不希望它一直推到数组中。

let randomFact;
let healthArray = []
$(".round-number")
.find("h3")
.each(function(i, el) {
let row = $(el).text().replace(/(s+)/g, " ");
row = $(el)
.text()
.replace(/[0-9]+. /g, "")
.trim();
healthArray.push(row);
});
randomFact = healthArray[
Math.floor(Math.random() * healthArray.length)
].toString();

您可以生成随机数,然后使用eq()直接从DOM中提取随机元素的文本。这将否定构建阵列的必要性。

let $h3 = $('.round-number h3');
let rnd = Math.floor(Math.random() * $h3.length);
let randomFact = $h3.eq(rnd).text().replace(/[0-9]+. /g, '').trim();

下面是一个工作示例:

let $h3 = $('.round-number h3');
$('button').on('click', () => {
let rnd = Math.floor(Math.random() * $h3.length);
let randomFact = $h3.eq(rnd).text().replace(/[0-9]+. /g, '').trim();
console.log(randomFact);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Get random</button>
<div class="round-number"><h3>Foo</h3></div>
<div class="round-number"><h3>Bar</h3></div>
<div class="round-number"><h3>Fizz</h3></div>
<div class="round-number"><h3>Buzz</h3></div>
<div class="round-number"><h3>Lorem</h3></div>
<div class="round-number"><h3>Ipsum</h3></div>

最新更新