我需要在数组中总结一些对象值。有的可以int
,而有的可能string
即:数组对象上的字符串值的总和
的JavaScript:
let array = [
{quantity: 1, amount: "24.99"}
{quantity: 5, amount: "4.99"},
]
四处堆栈溢出我发现this method(IM使用反应):
Array.prototype.sum = function (prop) {
var total = 0
for (var i = 0, _len = this.length; i < _len; i++) {
total += this[i][prop]
}
return total
};
let totalQuantity = array.sum("quantity");
console.log(totalQuantity);
虽然该作品很好,我需要为字符串amount
做同样的事情。由于我需要将amount
转换为浮点数,因此上述操作无效。反应过来抱怨Component's children should not be mutated.
不被JS忍者,我认为这会做一些法宝:
Array.prototype.sum = function (prop) {
var newProp = parseFloat(prop);
var total = 0
for (var i = 0, _len = this.length; i < _len; i++) {
total += this[i][newProp] // Surely this is wrong :(
}
return total
};
任何清洁的方式来实现这一目标?
我需要这样的:
let totalAmount = array.sum("amount");
好抓。我想知道是否有另一种方式,而不是使用'Array.prototype' – Sylar