JavaScript数组求和

7
我该如何使用JavaScript计算unitprice数组中填充的值之和?
以下是我的HTML代码:
   <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>

ID必须是唯一的!(是的,你可以) - Felix Kling
请使用“class”属性代替“id”属性。(在页面上不能有多个具有相同ID的元素。) - Šime Vidas
如果我将ID设为唯一标识,那么我该如何进一步操作呢?请记住,unitprice是动态的,就像我点击添加新行并创建另一个unitprice一样。因此,我需要它们的总和。 - Faizan
像 @Šime Vidas 一样使用独特的类...您可以在一个元素上拥有任意多个类。 - Mihai Iorga
1
@Faizan 页面上的所有ID必须是唯一的。为了解决这个问题,您可以使用CSS类作为标记或唯一属性。例如,您可以声明<input type="text" unitpricemarker="" name="unitprice"/>,现在您可以使用jQuery选择所有这样的字段 - $('input[unitpricemarker]') - AppleGrew
5个回答

40
如果您可以将值存储在数组中,则无需使用jQuery对它们进行求和。您可以使用数组对象上已经存在的方法来完成工作。
数组具有.reduce()方法。 文档: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce Array.reduce接受一个函数作为参数,该函数充当累加器回调。累加器函数接受4个参数(previousValue, currentValue, index, array)。您只需要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;
    };
}

我想要的是什么。楼主的原标题有点误导。 - frostymarvelous
这个回答值得更多的认可。谢谢derenard。 - backdesk
1
使用lambda表达式:var sum = sampleArray.reduce((e, i) => e + i) - aloisdg

5

将HTML中的id改为使用classid必须是唯一的):

<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
  });

14
var sum = arr.reduce(function(a, b) { return a + b; }, 0); 比 jQuery 的 each() 更快。 - Riking
1
甚至更短: 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;
}

你也可以这样写 for 循环:for(i = ups.length; i--;) - Felix Kling
@Felix 谢谢,那样更清晰了。我不确定为什么我之前写成那样哈哈。 - Paul

1

//这是您的数组输入值 array.push(input.val())

function array_sum(arr){
    var sum = 0;
   for(var i = 0; i < arr.length; i++){
        sum += parseInt(arr[i]);
    }
    return sum;
}

0

给你的<input>添加唯一的ID,像这样:

<input type="text" id="unitprice_1">
<input type="text" id="unitprice_2">
<input type="text" id="unitprice_3">

然后计算总和:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接