Javascript递归添加所有"总计"属性向上并返回给用户

时间:2018-01-31 06:13:33

标签: javascript recursion

我得到了以下数据,我需要返回递归总数(在本例中为60)。以下代码返回指向TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined的{​​{1}}。我认为我在这里使用的代码不适用于数组定义。如何将其转换为使用数组?

object

4 个答案:

答案 0 :(得分:3)

递归方式以及array.prototype.maparray.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