javascript - 从 <pre> 读取数字

标签 javascript html pre

我正在尝试计算预标记中数字数组中的某些数字。比如数一下有多少个数字是7或7以上。 例如我有这个

    <pre class="data">2 7 3 1 2
    6   6   2   5   3
    8   2   5   9   9
    5   10  5   6   10
    2   10  3   </pre>

我已经弄清楚如何以通用方式获取数字:

    document.getElementsByTagName ('PRE')[0].firstChild.data = document.getElementsByTagName ('PRE')[0].firstChild.data.replace (/\t+$/, '')

但我不知道如何获得个人数字。它是一个数组吗?或者我需要按空格解析的数字列表?

我看过这个帖子:Using <pre> tag to display data in columns?并尝试使用 for 循环抓取 $entry[i],但我无法读取单个数字。

最佳答案

以下将为您提供一个二维数组:

var str = document.getElementsByTagName('pre')[0].textContent;

str                                 // take the string and
    .split('\n')                    // break it into an array of lines;
    .map(function(line) {           // then transform each line by
        return line                 // taking the line,
            .trim()                 // removing leading and trailing spaces,
            .split(/\s+/)           // and breaking it into an array at whitespace,
            .map(Number);           // with each piece cast to a number.
     });

关于javascript - 从 <pre> 读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227574/

相关文章:

javascript - 使用javascript替换@后跟的文本

javascript - 设置iframe的内容

php - PHP脚本的安全性,嵌入式或其他

javascript - 在 pre 或 div 标签中设置指针位置

javascript - 不要推送类型为 null 的元素的属性

javascript - 使列表项水平放置,即使在小屏幕上也不会换行

javascript - 为什么我的JS函数不能正常工作?

html - css对齐图像重叠

html - 预标记在浏览器中不同

javascript - 从脚本更新时如何在 <pre> 中使用 html 标签