简体   繁体   English

获取以分号分隔的字符串中的数字并计算平均jQuery

[英]get numbers in string separated by semi-colon and calculate average jquery

I've got a string like so: 我有这样的字符串:

"45; 32; 31; 54" “ 45; 32; 31; 54”

I want to take these 4 numbers out of the string, then add them all together and divide by the number of numbers in the string in order to get the average. 我想从字符串中取出这4个数字,然后将它们全部相加并除以字符串中的数字数,以获得平均值。

How would I do this? 我该怎么做? There may be only 1 number (thus no need to average it), or there may be 10 numbers, I have no way of knowing how many numbers there will be in each one, except to say there will always be at least 1 number. 可能只有1个数字(因此无需求平均),或者可能有10个数字,除了说总是会有至少1个数字之外,我无法知道每个数字有多少个。

here is : 这是 :

var s="45;32;31;54";
var s_array=s.split(';');
var sum=0;
var avarage=0;
for(var i =0;i<s_array.length;i++){

  sum+=parseInt(s_array[i]); 
}
avarage=sum/s_array.length;

Simple answer is : 简单的答案是:

var data = "45; 32; 31; 54"; //select the string
var arr = data.split('; '); //split the string
var sum = 0;

$.each(arr, function( index, value ) {
    sum += parseFloat(value);
});

var avg = sum / (arr.length);
console.log(avg)

Steps : 1. Define variable of string 2. Split it in to array. 步骤:1.定义字符串的变量。2.将其拆分为数组。 3. Parse through array and add all the elements 4. Calculate Average :-) 3.遍历数组并添加所有元素4.计算平均值:-)

Try 尝试

var str = "45; 32; 31; 54";
var arr = str.split(';'); //split into array
console.log(arr);

var sum = arr.reduce(function(a, b) { return +a + +b }); //Calculate sum
var avg = sum / arr.length; // Calculate avg
console.log(avg);

DEMO DEMO

Note: Used +Variable to convert variable to number 注意:使用+Variable将变量转换为数字

You don't need jQuery for this kind of tasks, and you can do everything in one line, using reduce : 您不需要jQuery来执行此类任务,并且可以使用reduce在一行中完成所有操作:

var str = "45; 32; 31; 54";

var average = str.split("; ").reduce(function(avg, number, index) {
   return +avg + (number - avg) / (index + 1)
});

This is an incremental average, that is also useful if you have a lot of numbers and/or big numbers, so with regular averaging you could end up in overflow while you summing up the elements, this approach reduce that risk. 这是一个递增的平均值,如果您有很多数字和/或很大的数字,这也很有用,因此如果进行定期平均,则在对元素求和时可能会出现溢出,这种方法降低了这种风险。

For the browser doesn't support reduce the documentation above provides a shim – nowadays modern browsers support ES5, and for older browsers this kind of shim should be a must-have. 对于不支持该浏览器的浏览器, reduce上述文档提供了一个垫片-如今,现代浏览器支持ES5,对于较旧的浏览器,此类垫片应该是必须的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM