Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/90.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在我的JavaScript中添加搜索功能?_Javascript_Html - Fatal编程技术网

如何在我的JavaScript中添加搜索功能?

如何在我的JavaScript中添加搜索功能?,javascript,html,Javascript,Html,我正在使用JavaScript开发一个音乐播放器,并试图在我的页面中添加一个搜索栏,但到目前为止,我看到的每个教程都使用在HTML页面中创建的列表,而我使用JavaScript代码创建了一个列表,如下所示: const songs = [ "BlindingLights.mp3", "Boyfriend.mp3", "DontStartNow.mp3", "Intentions.mp3", "Physical" ] const createSongLis

我正在使用JavaScript开发一个音乐播放器,并试图在我的页面中添加一个搜索栏,但到目前为止,我看到的每个教程都使用在HTML页面中创建的列表,而我使用JavaScript代码创建了一个列表,如下所示:

const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp3",
    "DontStartNow.mp3",
    "Intentions.mp3",
    "Physical"
]

const createSongList = () => {
    const list = document.createElement('ol')

    for(let i = 0; i<songs.length; i++){
        const item = document.createElement('li')
        item.appendChild(document.createTextNode(songs[i]))

        list.appendChild(item)
    }

    return list
}

document.getElementById('songList').appendChild(createSongList())
const歌曲=[
“BlindingLights.mp3”,
“男朋友,mp3”,
“DontStartNow.mp3”,
“意图.mp3”,
“物理的”
]
const createSongList=()=>{
const list=document.createElement('ol')

对于(设i=0;i假设要从搜索字符串中筛选
歌曲
数组,可以使用此函数:

const歌曲=[
“BlindingLights.mp3”,
“男朋友,mp3”,
“DontStartNow.mp3”,
“意图.mp3”,
“物理的”
];
const searchSong=(值)=>{
返回songs.filter(song=>song.includes(value));
};

console.log(searchSong('B');
也许您可以为Array.prototype创建一个新函数
search
,使其更易于使用

Array.prototype.search = function (keyword) {
  return this.filter(text => text.toLowerCase().includes(keyword.toLowerCase().trim()))
}  
const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp6",
    "DontStartNow.mp5",
    "Intentions.mp3",
    "Physical"
];

songs.search('phy ')  // => ["Physical"]
songs.search(' MP3')  // =>  ["BlindingLights.mp3", "Intentions.mp3"]

1-您希望如何使用歌曲数组?2-您将在页面上的何处使用它?如果您可以将页面作为代码段上传给我们,并在此处指定您希望以这种方式使用它,它将更具描述性。我编辑了我的帖子,希望能更清楚一点:)在输入框中添加onChange listener,并将输入函数中的任何内容发送到搜索函数。我认为他想要的是重建搜索结构,并根据搜索结果过滤此搜索列表。这不应该那么简单。
Array.prototype.search = function (keyword) {
  return this.filter(text => text.toLowerCase().includes(keyword.toLowerCase().trim()))
}  
const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp6",
    "DontStartNow.mp5",
    "Intentions.mp3",
    "Physical"
];

songs.search('phy ')  // => ["Physical"]
songs.search(' MP3')  // =>  ["BlindingLights.mp3", "Intentions.mp3"]