如果你能在一个数组中的值,你不必使用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;
};
}
ID必须**唯一**! (是的,你可以) –
使用'class'属性而不是'id'属性。 (你不能有多个具有相同ID的元素在页面上。) –
好吧,如果我让ID唯一,那么我该怎么做呢?请记住,unitprice是动态的,就像我点击添加新行一样,它会创建另一个单位价格。所以我需要他们的总和。 – Faizan