我得到了以下数据,我需要返回递归总数(在本例中为60)。以下代码返回指向TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
的{{1}}。我认为我在这里使用的代码不适用于数组定义。如何将其转换为使用数组?
object
答案 0 :(得分:3)
递归方式以及array.prototype.map
和array.prototype.reduce
:
var data = [
{
total: 10,
moreData: {
total: 10
}
},
{
total: 10,
moreData: {
total: 10,
moreData: {
total: 10
}
}
},
{
total: 10
}
];
var sum = data.map(totInObj).reduce((m, o) => m + o, 0);
console.log(sum);
function totInObj(obj) {
return obj.moreData ? obj.total + totInObj(obj.moreData) : obj.total;
}
答案 1 :(得分:1)
您应该更改递归方法。
function sumUp(obj){
totalofall +=obj.total;
if(obj.moreData != undefined)
{
sumUp(obj.moreData);
}
}
object.children
没有data
属性。 data
是一个数组,您可以使用递归函数迭代它。
for(obj of data){
sumUp(obj);
}
最后,完整的代码看起来像。
var data = [
{
total: 10,
moreData: {
total: 10
}
},
{
total: 10,
moreData: {
total: 10,
moreData: {
total: 10
}
}
},
{
total: 10
}
];
var totalofall = 0;
function sumUp(obj){
totalofall +=obj.total;
if(obj.moreData != undefined)
{
sumUp(obj.moreData);
}
}
for(obj of data){
sumUp(obj);
}
console.log(totalofall);
答案 2 :(得分:0)
您需要处理数组项目和total
s而不是value
(内联解释)
function sumUp(object)
{
var totalValue=0; //keep a local variable instead of assigning a new property to object
if ( Array.isArray( object ) ) //if object is an array, iterate the same
{
object.forEach( s => ( totalValue += sumUp( s ) ) );
}
if ( object.moreData ) //check for moreData instead of children
{
totalValue += sumUp( object.moreData );
}
return totalValue + (object.total || 0); //sum of total instead of value
}
<强>演示强>
var data = [
{
total: 10,
moreData: {
total: 10
}
},
{
total: 10,
moreData: {
total: 10,
moreData: {
total: 10
}
}
},
{
total: 10
}
];
function sumUp(object)
{
var totalValue = 0;
if ( Array.isArray( object ) )
{
object.forEach( s => ( totalValue += sumUp( s ) ) );
}
if ( object.moreData )
{
totalValue += sumUp( object.moreData );
}
return totalValue + (object.total || 0);
}
console.log( sumUp( data ) );
答案 3 :(得分:0)
最简单的似乎是遍历数组,然后深入到对象中:
background:color:white;position:sticky