JavaScript求和函数
JavaScript sum function
我已经在数组的总和中堆叠了。代码在
下面function User(name,email) {
this.name = name;
this.email = email;
this.cartAmount = [];
this.total = 0;
}
User.prototype = {
constructor: User,
addCart: function(mrp){
this.cartAmount.push(mrp);
},
changeEmail: function(newmail){
this.email = newmail;
},
showCart: function() {
var cart = this.cartAmount.length >0 ? this.cartAmount.join("tk,") : "No product in the cart";
return this.name+" has "+cart+" in his cart.";
},
intotal: function(){
for(var n in this.cartAmount){
this.total += this.cartAmount[n];
return this.total;
}
}
};
athar= new User("Athar Jamil", "atharjamil@gmail.com");
console.log(athar.name);
athar.changeEmail("atharjamil@yahoo.com");
console.log(athar.email);
athar.addCart(20);
athar.addCart(50);
athar.addCart(80);
console.log(athar.intotal());
结果显示只有20。有什么问题吗?
您的for
太早了,因此您的CC_2循环只运行一次并返回购物车中的第一件商品。
试试这个:
intotal: function(){
for(var n in this.cartAmount){
this.total += this.cartAmount[n];
}
return this.total;
}
不要使用this.total
。如果多次调用这个方法,每次调用的总数都会增加。您至少应该在您的方法的顶部放置一个this.total = 0
。
我个人会这样写:
intotal: function(){
var out = 0;
for(var n in this.cartAmount){
out += this.cartAmount[n];
}
return out;
}
使用Array.prototype.reduce()
可以大大简化该函数:
intotal: function() {
return this.cartAmount.reduce((a, b)=> a + b)
}
从MDN: reduce()
方法对累加器和数组的每个值(从左到右)应用一个函数,以将其减少为单个值。
在这里,您将一个箭头函数传递给reduce
方法,该方法接受两个参数:a
和b
,并返回它们的总和。
intotal函数返回cartAmount数组的第一个元素。将intotal函数的返回语句置于for循环之外
function sum(){
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(pre,curr){
if(!isNaN(curr)){
return pre+curr;
}
else
{
throw Error("Non-Numeric arguments"+curr);
}
},0)
}
var result = sum(12,13,14); //pass any number of parameter to sum
alert("Sum Is:"+result);
https://www.npmjs.com/package/mnjs
首先从mnjs包中导入sum函数
<script src="https://cdn.jsdelivr.net/npm/mnjs/browser/index.js"></script>
或
const {sum} = require('mnjs')
或
从'mnjs'中导入{sum}
然后使用sum函数,如下所示:
const cartAmount = [1, 4, 2]
sum(cartAmount) // returns 7
https://runkit.com/dr-montasir/mnjs-sum-function 相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 如何在JavaScript中使用此函数对范围内的所有数字求和
- 使用绑定的简单JavaScript/jQuery求和函数
- Javascript Array 的求和函数问题
- 角度 - 使用函数对数字求和并将其放入视图中
- onChange函数,求和值
- Datatables插件求和函数
- 对多个函数求和
- 试图创建一个对数字求和的Javascript函数
- 对javascript构造函数中的参数求和并返回total
- 函数在不使用parseInt的情况下求和以2为基数的数字的值
- 如何在javascript中求和两个不同的函数
- 如何使用jquery-onlick函数对表单文本字段数组中的值求和
- 当对数组元素求和时,递归函数根据顺序返回不同的值
- 如何在异步函数中对 Javascript 数组的值求和
- 可变curry求和函数
- JavaScript求和函数
- JQuery函数格式和求和或2个文本框的问题