javascript - 如何遍历对象内部的数组?
问题描述
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
解决方案
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(","));
});
推荐阅读
- ios - 如何在 iOS 上为此 lang ibpreviewdocumenteditordoublelengthpseudolocale 启用本地化
- canvas - 有没有办法让chart.js中的饼图的外边框颜色与段之间的边框颜色不同?
- django - 如何在 GitHub 操作中编写 blob 以自动标记拉取请求?
- rabbitmq - 具有长 ETA 和 RabbitMQ 的 Celery 任务
- kotlin - 在 kotlin 中使用 Run 的 Elvis 运算符
- python - Python sharepoint 连接 - 无法访问
- sql-server - 为什么这个 T-SQL 查询在 Synapse 中不起作用?
- postgresql - 从 .NET 交互式笔记本中的 SQL 单元查询 postgres 数据库
- javascript - wordpress 上同时有两个活动链接
- c++ - 从分配器返回的内存指针算法