3 回答

TA貢獻1810條經驗 獲得超4個贊
有多個問題
假設對象有一個變量 obj
var loop = () => {
var arr = []
for (var i = 0 ; i< obj.messages.length; i ++) { //messages is a key of an object, so messages is undefined, it should be obj.messages.
arr.push(messages[i]) //wrong index, you should push `i` and not 1
}
return arr; // loop() is a function, causing endless recursion, causing stack overflow!
console.log(arr) // will never print since function already returns!; move before return if you want it to print
}

TA貢獻1784條經驗 獲得超2個贊
你可以使用解構,它簡短而簡單。
var obj = { "messages": [
{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}
]
};
var arr = [...obj.messages];
console.log(arr);
添加回答
舉報