我需要將此代碼轉換為回圈,但我不知道如何。
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));
uj5u.com熱心網友回復:
你在哪里卡住?也許這可以幫助您入門。
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/431118.html
標籤:javascript 循环 目的 递归
