首页 > 解决方案 > 如何遍历对象内部的数组?

问题描述

const obj = {
  "urls": [{
      "url": "youtube.com",
      "category": ["react js", "javascript"]
    },
    {
      "url": "facebook.com",
      "category": ["react js", "javascript"]
    }
  ]
}

const loop = (a) => {
  for (let j = 0; j < a.length; j++) {
    console.log(a[j].url);
  }
  return;
}

for (let i in obj) {
  console.log(i + " " + loop(obj[i]));
}

输出是:

"youtube.com"
"facebook.com"
"urls undefined"

为什么loop函数首先执行?它应该只在第二个循环内运行:

for(let i in obj){
console.log(i + " " + loop(obj[i])  );
}

我希望能够输出:

urls : youtube.com reactjs,javascript

标签: javascript

解决方案


With short code often the easiest thing to do to debug it is to just do a basic walkthrough of your code by hand to see if it's really doing what you want it to.

You'll notice that the second loop simply performs:

console.log("urls" + " " + loop(obj["urls"])  );

This will result in loop being called:

console.log(obj["urls"][0].url);
console.log(obj["urls"][1].url);
return; // returns undefined

Which will output:

youtube.com
facebook.com

Only then (after the first two logs from inside the loop call) will the initial console.log take place with the return value of loop:

console.log("urls" + " " + undefined /*loop(obj["urls"])*/  );

Giving your last line of output:

urls undefined

As for why loop gets called before the console.log("urls" + ...), think about it, how can console.log know what to output, if to output it it needs to have called loop? loop has to come first.


It sounds like you were trying to do something like this:

const obj = {
  "urls": [{
      "url": "youtube.com",
      "category": ["react js", "javascript"]
    },
    {
      "url": "facebook.com",
      "category": ["react js", "javascript"]
    }
  ]
}

// Constructs a string representation of the list of categories
const loop = (a) => {
  o = "";
  for (let j = 0; j < a.category.length; j++) {
    o += "," + a.category[j];
  }
  return o.substring(1);
}

// Call loop for each url in obj
for (let i in obj.urls) {
  console.log("urls : " + obj.urls[i].url + " " + loop(obj.urls[i]));
}

This can be tidied up using join instead of your loop function and by using Array.prototype.forEach:

const obj = {
  "urls": [{
      "url": "youtube.com",
      "category": ["react js", "javascript"]
    },
    {
      "url": "facebook.com",
      "category": ["react js", "javascript"]
    }
  ]
}

// Call loop for each url in obj
obj.urls.forEach(urlObj => {
    console.log("urls : " + urlObj.url + " " + urlObj.category.join(","));
});


推荐阅读