{
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
var loop = () => {
var arr = []
for (var i = 0 ; i<messages.length; i ++) {
arr.push(messages[1])
}
return loop()
console.log(arr)
}
我需要遍历此对象并仅将消息推送到新数组中
相同
答案 0 :(得分:1)
arr.push(messages[1])
1应该是i,您每次都获取相同的索引
答案 1 :(得分:0)
有多个问题
假设对象具有变量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
}
答案 2 :(得分:0)
请不要误解,但是您的代码在不同的地方太混乱了,以至于我建议您再看看JavaScript的绝对基础。
{
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
去掉外部花括号,然后使用var messages = [...]
将数组设置为变量messages
。
var messages = [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
您永远不会调用loop
是引用的匿名箭头功能。通过loop()
调用它。
这将导致无限循环,因为您的返回值实际上是一个函数调用,一次又一次地调用引用的函数。
您在到达console.log()
之前就从函数返回,因此不会记录任何内容。
您应该按messages[i]
,因为messages[1]
总是按第二个元素(JS索引从零开始)
总结起来,下面是经过清理和运行的代码(实际上什么也没做,因为它只是将所有元素从一个数组复制到另一个数组):
var messages = [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}];
var loop = () => {
var arr = []
for (var i = 0; i < messages.length; i++) {
arr.push(messages[i])
}
// return loop()
console.log(arr)
}
loop();
答案 3 :(得分:0)
您可以使用解构,它很简短。
var obj = { "messages": [
{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}
]
};
var arr = [...obj.messages];
console.log(arr);