Mic*_*ael 6 javascript methods
所以,我正在测试 JS includes() 方法,所以我创建了一个搜索输入字段,我可以在其中搜索我使用实时重新渲染创建的笔记。现在我的问题是:当我根本不传递搜索文本时,会显示所有注释,但是当我输入一个字符或单词时,这些注释会立即被过滤掉。示例代码:
const filters = {
searchText: ''
}
// Render application notes
const renderNotes = (notes, filters) => {
const filteredNotes = notes.filter((note) => {
return note.title.toLowerCase().includes(filters.searchText.toLowerCase())
})
document.querySelector('#notes').innerHTML = ''
filteredNotes.forEach((note) => {
const noteEl = generateNoteDOM(note)
document.querySelector('#notes').appendChild(noteEl)
})
}
Run Code Online (Sandbox Code Playgroud)
我从中了解到,在这种情况下总是返回 true .. 希望对此主题进行任何澄清!
谢谢!
为了一致性,该.includes()函数必须匹配 的功能.indexOf(),并且.indexOf()始终匹配任何目标字符串中的空字符串。来自 MDN:
空字符串 searchValue 将匹配 0 和 str.length 之间的任何索引。
这有点违反直觉,但请考虑一下:
var str = "something";
console.log(str.includes("")); // Imagine this returns false ...
str += "";
console.log(str.includes("")); // !!
Run Code Online (Sandbox Code Playgroud)