需要将 .innerHTML 的结果转换为 javascript 上的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14617221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need to convert result of .innerHTML to number on javascript
提问by user2027553
I have a html that contains tables like the following example
我有一个包含表的 html,如下例所示
<td class="topiccell">
<span class="topicnormal">
<a class="value" href="/topic/?lang=en&action=viewtopic&topic=http%3A%2F%2Fwww.wandora.org%2Fsparql%2Fresultset%2Fliteral%2F40">
40
</a>
</span>
</td>
<td class="topiccell">
<span class="topicnormal">
<a class="value" href="/topic/?lang=en&action=viewtopic&topic=http%3A%2F%2Fwww.wandora.org%2Fsparql%2Fresultset%2Fliteral%2F40">
3
</a>
</span>
</td>
and I need to parse 40, 3 and another 75 numbers using .innerHTML. Then I would like to make a sum of all 75 numbers. I used the following
我需要解析 40、3 和另外 75 个数字.innerHTML。然后我想对所有 75 个数字求和。我使用了以下
var valuelements = document.getElementsByClassName("value");
var features = new Array(valuelements.length);
for (var i=0; i<=features.length; i++){
var val = valuelements[i].innerHTML;
var counter = counter + val;
}
document.write(counter);
and the result was like 40 3 etc.... tried parseInt, parseFloat, .valuebut the result always was NaN.Any suggestions?
其结果就像40 3等....尝试parseInt,parseFloat,.value但结果始终是NaN.有什么建议?
回答by the system
You need to initialize counterwith a starting number, otherwise you're performing math on undefined.
您需要counter使用起始数字进行初始化,否则您将在 上进行数学运算undefined。
var counter = 0;
And then in the loop, use parseInt, parseFloat, or a direct number conversion on the .innerHTMLvalue.
然后在循环中,对值使用parseInt、parseFloat或直接数字转换.innerHTML。
var counter = 0;
for (var i=0; i<features.length; i++){
counter += parseFloat(valuelements[i].innerHTML);
}
In a modern browser, you could do this:
在现代浏览器中,您可以这样做:
var count = [].reduce.call(valueelements, function(c, v) {
return c + parseFloat(v.innerHTML);
}, 0);
回答by elclanrs
Try something like this, using a more functional approach:
尝试这样的事情,使用更实用的方法:
var sum = [].map.call(valuelements, function(v) {
return +v.textContent; }).reduce(function(a, b) { return a + b; });

