猿问

我需要知道我在这里做错了什么

{

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

}

我需要遍历这个对象并只获取推送到新数组中的消息


相同的


慕丝7291255
浏览 318回答 3
3回答

翻翻过去那场雪

arr.push(messages[1])1 应该是 i,你每次都抓取相同的索引

慕莱坞森

有多个问题假设对象有一个变量 objvar loop = () => {&nbsp; var arr = []&nbsp; 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.&nbsp; &nbsp; arr.push(messages[i]) //wrong index, you should push `i` and not 1&nbsp; }&nbsp; return arr; // loop() is a function, causing endless recursion, causing stack overflow!&nbsp; console.log(arr) // will never print since function already returns!; move before return if you want it to print}

一只斗牛犬

你可以使用解构,它简短而简单。var obj = { "messages": [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "msgFrom": "13223821242",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "msgBody": "Hi there"&nbsp; &nbsp; &nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "msgFrom": "Bill",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "msgBody": "Hello!"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]};var arr = [...obj.messages];console.log(arr);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答