我正在开发一个对文本中的所有数字求和的函数:
'use strict';
var sum = function(text, regex) {
var match;
return !!(match = text.match(regex || /\d+/g)) ?
match.reduce(function(prev, curr) {
return +prev + +curr;
})
: 0;
}
console.log(sum('1 12 40'));
console.log(sum('10 12 40'));
console.log(sum('1 12 510'));
console.log(sum('LLLLLLLL'));
console.log(sum('10 1'));
并且不工作它与点的数字:
'use strict';
var sum = function(text, regex) {
var match;
return !!(match = text.match(regex || /\d+/g)) ?
match.reduce(function(prev, curr) {
return +prev + +curr;
})
: 0;
}
console.log(sum('1.10 12.40 40.30'));
所以,我想寻求帮助。我怎样才能用指针对数字求和?
谢谢。
最佳答案
使用正则表达式来匹配带小数点的数字
var sum = function(text, regex) {
return (text.match(regex || /\d*(?:\.\d*)?/g) || [])
.reduce(function(prev, curr) {
return prev + +curr;
}, 0);
}
document.write(sum('1.10 12.40 40.30'));
关于javascript - 对正则表达式产生的所有数字求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097114/