Javascript 数组求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7203684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:19:49  来源:igfitidea点击:

Javascript Array Sum

javascript

提问by Faizan

How I can sum up the values filled in unitprice array using javascript Here is my html.

我如何总结使用 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>

采纳答案by JJ.

Change your HTML to use classinstead of id(idmust be unique):

更改您的 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>

Then you can total via JavaScript (using jQuery .each()function):

然后你可以通过 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
  });

回答by derenard

If you can get the values in an array, you don't have to use jQuery to sum them. You can use methods already present on the array object to do the work.

如果可以获取数组中的值,则不必使用 jQuery 对它们求和。您可以使用数组对象上已有的方法来完成这项工作。

Arrays have a .reduce() method. Documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

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

Array.reduce accepts a function as an argument that acts as an accumulator callback. The accumulator function accepts 4 arguments (previousValue, currentValue, index, array). You only need 2 of them to sum. Those 2 arguments are previousValue and currentValue.

Array.reduce 接受一个函数作为参数,作为累加器回调。accumulator 函数接受 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;
});

If you are faced with a compatibility issue where the target environment doesn't support ECMAScript 5 or above additions, use the prototype definition defined in the MDN article linked. (Appended below)

如果您遇到目标环境不支持 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;
    };
}

回答by Paul

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

回答by nobody

Give your <input>s unique ids like this:

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

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

Then compute the sum:

然后计算总和:

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