因此,我正在测试 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)
})
}
我从这里了解到,在这种情况下总是返回 true .. 希望对此主题有任何澄清!
谢谢!
最佳答案
.includes()
函数必须匹配 .indexOf()
的功能以保持一致性,并且 .indexOf()
始终匹配任何目标字符串中的空字符串。 From MDN :
An empty string searchValue will match at any index between 0 and str.length.
这有点违反直觉,但考虑一下:
var str = "something";
console.log(str.includes("")); // Imagine this returns false ...
str += "";
console.log(str.includes("")); // !!
关于javascript - 当我将一个空字符串传递给 includes (""时)它总是返回 true 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51596236/