簡體   English   中英

如何將遞歸轉換為循環?

[英]How to convert recursion to loop?

我需要將此代碼轉換為循環,但我不知道如何。

 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));

你卡在哪兒了? 也許這可以幫助您入門。

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