【问题标题】:How to get random single result from multiple rows text from web scraping using Javascript?如何使用Javascript从网络抓取的多行文本中获取随机单个结果?
【发布时间】:2022-08-04 22:21:11
【问题描述】:

有什么方法可以让我立即从行中获取随机的单个结果并将其输出,而无需推送到 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();

    标签: javascript jquery


    【解决方案1】:

    您可以生成随机数,然后使用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();
    

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 1970-01-01
      • 2017-12-30
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      相关资源
      最近更新 更多