2011-08-26 100 views
6

我如何总结使用javascript在unitprice数组中填充的值 这是我的html。Javascript Array Sum

<td> 
     <input type="text" style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" id="unitprice" name="unitprice[]"> 
    </td> 
    <td> 
     <input type="text" style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" id="unitprice" name="unitprice[]"> 
    </td> 
+0

ID必须**唯一**! (是的,你可以) –

+0

使用'class'属性而不是'id'属性。 (你不能有多个具有相同ID的元素在页面上。) –

+0

好吧,如果我让ID唯一,那么我该怎么做呢?请记住,unitprice是动态的,就像我点击添加新行一样,它会创建另一个单位价格。所以我需要他们的总和。 – Faizan

回答

5

更改HTML使用class代替idid必须是唯一的):

<td> 
    <input type="text" 
     style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" maxlength="4" 
     class="unitprice" name="unitprice[]"> 
</td> 
<td> 
    <input type="text" 
     style="width: 60px; background: none repeat scroll 0% 0% rgb(255, 255, 255);" 
      maxlength="4" class="unitprice" name="unitprice[]"> 
</td> 

然后你就可以通过JavaScript总额(使用jQuery .each()功能):

var totalUnitPrice = 0; 

$('.unitprice').each(function(index) { 
    totalUnitPrice += parseInt($(this).val()); // parse the value to an Integer (otherwise it'll be concatenated as string) or use parseFloat for decimals 
    }); 
+0

工作得很好!谢谢 – Faizan

+12

'var sum = arr.reduce(function(a,b){return a + b;},0);'比jQuery的each()更快。 – Riking

+0

甚至更​​短 var sum = reduce((a,b)=> a + b,0);' – evgpisarchik

2
function getSum(){ 
    var ups = document.getElementsByName('unitprice[]'), sum = 0, i; 
    for(i = ups.length; i--;) 
     if(ups[i].value) 
      sum += parseInt(ups[i].value, 10); 
    return sum; 
} 
+0

你也可以将'for'循环写为'for(i = ups.length; i - ;)' –

+0

@Felix是的,谢谢你,这样干净得多。我不知道为什么我按照我做的方式写了它。 – Paulpro

0

给你的<input> s独一无二的ids li柯本:

​​

然后计算总和:

var i = 1; 
var sum = 0; 
var input; 
while((input = document.getElementById('unitprice_'+i)) !== null) { 
    sum += parseInt(input.value); 
    ++i; 
} 
alert(sum); 
35

如果你能在一个数组中的值,你不必使用jQuery来概括他们。您可以使用数组对象上已有的方法来完成这项工作。

数组有一个.reduce()方法。 文档: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

Array.reduce接受函数作为充当累加器回调的参数。累加器函数接受4个参数(previousValue,currentValue,index,array)。你只需要其中的2个就可以了。这2个参数是previousValue和currentValue。

var sampleArray = [1, 2, 3, 4, 5]; 
var sum = sampleArray.reduce(function(previousValue, currentValue){ 
    return currentValue + previousValue; 
}); 

如果你面对的是一个兼容性问题,其中目标环境不支持的ECMAScript 5或以上的增加,使用MDN文章链接中定义的原型定义。 (附在下面)

if (!Array.prototype.reduce) { 
    Array.prototype.reduce = function reduce(accumulator){ 
    if (this===null || this===undefined) throw new TypeError("Object is null or undefined"); 
    var i = 0, l = this.length >> 0, curr; 
    if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception." 
     throw new TypeError("First argument is not callable"); 
    if(arguments.length < 2) { 
     if (l === 0) throw new TypeError("Array length is 0 and no second argument"); 
     curr = this[0]; 
     i = 1; // start accumulating at the second element 
    } 
    else 
     curr = arguments[1]; 
    while (i < l) { 
     if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this); 
     ++i; 
    } 
    return curr; 
    }; 
} 
+0

我在问什么。 OP的原始标题有点误导。 – frostymarvelous

+0

这个答案值得更多的认可。感谢derenard。 – backdesk

+1

使用lambda:'var sum = sampleArray.reduce((e,i)=> e + i)' – aloisdg