【发布时间】:2022-01-21 06:29:40
【问题描述】:
我正在尝试制作一个简单的网站(没有 CSS3)来搜索数组中的项目。我实现这一目标的方法是在数组中的项目的“标题”或“描述”属性中进行搜索。如果标题包含输入中的关键字,我的预期结果是在控制台中获得 titleOfItem + 'fizz'。相反,我收到以下错误:
这是我的 HTML5 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input id="keywordText" type="text">
<button id="submit" onclick="search()">Search</button>
<script src="script.js"></script>
</body>
</html>
这是我的 JS 代码:
const items = {
john:{title:'john', desc:"doe", elem:document.getElementById('john')},
jane:{title:'jane', desc:"doe", elem:document.getElementById('jane')}
}
let allItems = []
for (var key in items) {
allItems.push(items[key])
}
function search() {
let keyword = document.getElementById('keywordText').value;
for (let count = 0; allItems.length; count++) {
let titleOfItem = allItems[count].title
if (titleOfItem.includes(keyword)) {
console.log(titleOfItem + ' fizz')
} else {
console.log(titleOfItem + ' buzz')
}
}
}
我在这段代码中做错了什么吗?另外,出于组织目的,有没有办法直接从第一个数组中获取这些信息?
【问题讨论】:
-
这就是你应该使用
for..Each,for..of的原因,这样你就不必关心count < allItems.length之类的无关紧要的事情,只需编写逻辑即可。您也可以将 forEach 用作allItems.forEach(({ title }) => { if(title.includes(keyword)) console.log( title + ' fizz' ) else console.log( title + ' buzz' ) }) -
您已将以下答案标记为已接受。这表明问题已经解决。您也不需要将该信息添加到您的问题正文中。
标签: javascript html arrays sorting search