简体   繁体   English

如何将递归转换为循环?

[英]How to convert recursion to loop?

I need convert this code to loops, but i have no idea how.我需要将此代码转换为循环,但我不知道如何。

 let object = { x: 250, a: 5, b: 5, c: { ac: 5, acd: 10 } }; let objectPropertiesSum = object => { let sum = 0; for (const value of Object.values(object)) { if (typeof(value) === "number") { sum += value; } else if (typeof(value) === "object") { sum += objectPropertiesSum(value); } } return sum; }; console.log(objectPropertiesSum(object));

Where are you getting stuck?你卡在哪儿了? Maybe this can help you get started.也许这可以帮助您入门。

function sumValues(obj) {
  const stack = [obj]
  let sum = 0
  let o, v
  while (stack.length) {  /* as long as there are items on the stack */
    o = /* get an item off the stack */
    for (v of /* obj values */) {
      if (/* v is a number */)
        /* update the sum */
      else if (/* v is an object */)
        /* update the stack */
      else
        /* v is not a Number or an Object */
    }
  }
  return sum
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM