为什么这个 JS 数组在 Vuex 中不减少
Why doe this JS array not reduce in Vuex
我有一个 Vuex 商店,其中有一个名册对象。 roster 对象有一个 subteam 对象数组。每个子团队对象都有一个位置对象数组。如何计算总仓位?
见下文getter:
totalPositions : function (state) {
let reducer = (accumulator, subteam) => accumulator + subteam.positions.length;
return state.roster.subteams.reduce(reducer);
}
当我记录结果时,我得到类似这样的信息:
"[object Object]33010600000000000000000000000000000"
字符串中的数字与位置数组的实际长度非常相似,但不完全相同。我尝试使用 parseInt(即使 array.length 应该是一个整数):
let reducer = (accumulator, subteam) => {
return accumulator + parseInt(subteam.positions.length,10);
};
没用。
您必须将初始值传递给 reduce
function。
totalPositions : function (state) {
const reducer = (accumulator, subteam) => accumulator + subteam.positions.length;
return state.roster.subteams.reduce(reducer, 0);
}
If no initial value is supplied, the first element in the array will be used.
由于subteam
看起来像一个对象,所以在加法中将其转化为字符串[object Object]
。
const obj = {};
console.log(obj + 13)
// => "[object Object]13"
然后说 "[object Object]3" + 3
是 "[object Object]33"
,等等,因为累加器现在是一个字符串。
我强烈建议您观看 CodeMash 2012 中 Gary Bernhardt 的 Wat lightning talk。
我有一个 Vuex 商店,其中有一个名册对象。 roster 对象有一个 subteam 对象数组。每个子团队对象都有一个位置对象数组。如何计算总仓位?
见下文getter:
totalPositions : function (state) {
let reducer = (accumulator, subteam) => accumulator + subteam.positions.length;
return state.roster.subteams.reduce(reducer);
}
当我记录结果时,我得到类似这样的信息:
"[object Object]33010600000000000000000000000000000"
字符串中的数字与位置数组的实际长度非常相似,但不完全相同。我尝试使用 parseInt(即使 array.length 应该是一个整数):
let reducer = (accumulator, subteam) => {
return accumulator + parseInt(subteam.positions.length,10);
};
没用。
您必须将初始值传递给 reduce
function。
totalPositions : function (state) {
const reducer = (accumulator, subteam) => accumulator + subteam.positions.length;
return state.roster.subteams.reduce(reducer, 0);
}
If no initial value is supplied, the first element in the array will be used.
由于subteam
看起来像一个对象,所以在加法中将其转化为字符串[object Object]
。
const obj = {};
console.log(obj + 13)
// => "[object Object]13"
然后说 "[object Object]3" + 3
是 "[object Object]33"
,等等,因为累加器现在是一个字符串。
我强烈建议您观看 CodeMash 2012 中 Gary Bernhardt 的 Wat lightning talk。