【发布时间】:2021-03-03 21:20:42
【问题描述】:
我勉强编写了这段代码,尽管它几乎可以正确地工作。不过,我真的需要您的帮助,使其更具可读性和意义。\
附言
我的天啊,我已经添加了大量的评论,但是 stackoverflow 的算法决定我需要,不,不......我必须在这里添加更多无用的文本。那么 Stackoverflow 的算法,够了吗?\
附言
对不起...
//creating tree of user's properties
//getting users
const request = "https://jsonplaceholder.typicode.com/users";
const xhr = new XMLHttpRequest();
xhr.open("GET", request);
xhr.send();
//when got users render them
xhr.onload = () => {
//getting the root element
const root = document.getElementById("root");
//parsing them into the object
JSON.parse(xhr.response).forEach((user) => {
//=========================================
//creating ul tag for each user <ul>
const ul = document.createElement("ul");
//iterating each users properties
for (const property in user) {
// ====================================
// for each property of a user creating li tag <li>
const listItem = document.createElement("li");
const value = user[property];
// if any property instance of Object,
// then render propery : value
if (!(user[property] instanceof Object)) {
listItem.innerHTML = `${property}: ${value}`;
} else {
//else if property is Object render just name of the property
listItem.innerHTML = `${property}:`;
}
// I know that this "if" statement is peace of unacceptable code
// that's why I'm here to ask you for help
if (user[property] instanceof Object) {
//========================================
//we have 2 Object props, address and company
//here we catch them and iterate each property
if (Object.hasOwnProperty.call(user, property)) {
//=========================================
//creating mini-child ul tag for address and company
const ulmini = document.createElement("ul");
//for each prop of adress or company creating newListItem that is <li> tag
for (const prop in value) {
const newItem = value[prop];
const newListItem = document.createElement("li");
newListItem.innerHTML = `${prop}: ${newItem}`;
//append all <li> tags
ulmini.appendChild(newListItem);
}
listItem.appendChild(ulmini);
}
}
//appending user's all properties
ul.appendChild(listItem);
}
// appending all list of users
root.appendChild(ul);
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>doc</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
【问题讨论】:
-
“那么 Stackoverflow 的算法,这就够了吗?” - 与其添加不必要的垃圾,不如看看 Help section 中的 What topics can I ask about here? 和 How do I ask a good question? 哪个应该解释为什么 “算法” 期望的文本比 “我勉强管理...”
-
代码审查是codereview.stackexchange.com的话题
-
您是否考虑阅读它们而不是解决您收到的消息?
-
看他是新来的平台他可能错过了消息,希望他下次以正确的格式将其发布到正确的位置,但这样问可能会吓跑新人。不想开始任何事情只是想表达我的意见。 @利亚姆
-
下一次,请注意内容警告的内容,而不是想办法让它们安静下来。系统试图要求你更具体地说明你认为可以改进的地方,或者为什么 - 像你一样随意输入文字只是对每个花费大量时间策划的人说“我不关心规则”网站。请不要再这样做了。