如何计算字符串中的数字 [英] How to calculate numbers in string

查看:91
本文介绍了如何计算字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串13-2-10-7-3,其中的数字由-分隔.

I have such string 13-2-10-7-3 where numbers delimited by -.

我想知道从javascript中的字符串计算所有数字的sum的最佳方法是什么?

I am wondering what is the best way to calculate the sum of all numbers from the string in javascript?

推荐答案

以下是将-拆分字符串的函数.然后浏览所有结果并添加它们.

Here's a function which will split your string by the -. Then go through all the results and add them.

function add(string){ 
    return string.split('-').reduce(function(a,b){return+a+(+b); });  
}

这将使用正则表达式从字符串中提取数字.然后它将使用.reduce()添加它们.不复杂. +a+(+b)会将ab转换为JavaScript数字,然后添加它们. +var将使变量从字符串到数字.据我所知,这是最短的方法.

This will use a regex to extract the numbers from the string. Then it will add them using .reduce(). not to complicated. The +a+(+b) will convert a and b to JavaScript numbers and then add them. +var will make a variable from a string to a number. This is the shortest method you could achieve as far as I know.

如果您不支持.reduce()功能,请使用应支持每个浏览器的备用代码:

If you can't support the .reduce() function, use the alternate code which should support every browser:

function add(string) {
    var strings = string.split('-'),
        sum = 0,i;
    for (i = 0; i < strings.length; i +=1 ) {
        sum += (+strings[i]);
    }
}

速度:〜0.062秒

小提琴

这篇关于如何计算字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆