我正在尝试计算预标记中数字数组中的某些数字。比如数一下有多少个数字是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/