gpt4 book ai didi

javascript - 过滤对象并将结果显示到 DOM (JS)

转载 作者:行者123 更新时间:2023-12-03 02:01:37 25 4
gpt4 key购买 nike

    ***HTML***

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToDos</title>
</head>
<body>
<h1>Todos....</h1>

<script src='todo-app.js'></script>
</body>
</html>






****JS***

const todos =[
{
text: 'Order Cat food',
completed: false
},
{
text: 'Clean Kitchen',
completed: true
},
{
text: 'Buy food',
completed: true
},
{
text: 'Do work',
completed: false
},
{
text: 'excercise',
completed: false
}
]

//任务//你还剩下 3 个待办事项 [p element] //为上面的每个待办事项添加一个 p(使用对象的文本值作为段落的可见文本)

*** what I have so far*****

document.createElement('p')
let pt = todos.forEach(function (t){
if(t.completed == true){
let pt = t

}

})
console.log(pt)

下午好,

我正在尝试完成这项挑战,但遇到了困难。我试图获取已完成的待办事项并在 HTML 上显示待办事项的文本,然后显示未完成的待办事项(错误)并将这些待办事项显示为需要在 html 中完成的待办事项。

我能够过滤掉具有 true 的待办事项并在控制台中记录它们。但我无法退出该功能并使用它们来显示它。

当我尝试调用 pt 时,它说它未定义。我不明白它什么时候包含所有代码。我猜我必须使用我仍在学习的“this”关键字,并且还没有完全理解如何自信地实现它。

我的问题是如何使用 'pt' 变量将已完成的待办事项输出到 html 中,然后创建另一个变量来输出未完成的待办事项。我知道这样做,错误的待办事项基本上就是真实的待办事项,例如

todos.forEach(function(f){
if(f.completed == false){
console.log(f)
*** this should return all the todo's that have the property boolean of false if i'm not mistaken.
}}

附注对困惑感到抱歉。感谢您的任何意见。

最佳答案

您可以将其分成更小的部分(处理附加完整的待办事项,然后附加它们),但您可以执行以下操作:

const todos = [{
text: 'Order Cat food',
completed: false
},
{
text: 'Clean Kitchen',
completed: true
},
{
text: 'Buy food',
completed: true
},
{
text: 'Do work',
completed: false
},
{
text: 'excercise',
completed: false
}
]

// get element you want to append to
var completedSection = document.getElementById('completed');

function handleTodos(array, location) {
var newArray = [];
// loop through array
array.forEach(function(item) {
// check if item.completed exists
if (item.completed) {
// if it does, append the item to the UL that was added to html
location.append(document.createElement("LI").innerHTML = item.text + ', ')
} else {
// if completed doesn't exist, push that to new array
newArray.push(item);
}
});
// return new array with incomplete tasks
return newArray;
}

var incompleteTasks = handleTodos(todos, completedSection);

console.log(incompleteTasks)
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ToDos</title>
</head>

<body>
<h1>Todos....</h1>
<!-- added to place completed tasks under, this could be created with js too. -->
<ul id="completed"></ul>

<script src='todo-app.js'></script>
</body>

</html>

希望这有助于回答您的问题!

关于javascript - 过滤对象并将结果显示到 DOM (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49986132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com