我有一个.js文件看起来如图所示(缩短为simplfication)
var albums=
"tracks":[
{"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3",
"lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"}
{"title":"Robin","mp3":"Birdsong-Robin.mp3",
"lyrics":"Unusually among British birds, both the male and the femaale robins sing"},
]
我需要创建一个查看文件的功能,并允许我选择其中一首歌曲,因为在其中找到了关键字。到目前为止我所拥有的是:
此函数采用字符串,使用循环查看文件,现在,如果找到了歌曲的名称,则会发出警告
function searchIt("str") {
for (var i in list) {
if(albums[i].lyrics.indexOf(str)){
alert(albums.tracks.title)
}
}
}
任何帮助都会受到赞赏,因为我很困惑。感谢
答案 0 :(得分:1)
你有一堆语法错误,你应该阅读MDN上的对象表示法和数组。
我让它像这样工作
var tracks = [
{
title:"Dunnock",
mp3:"Birdsong-Dunnock.mp3",
lyrics:"The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
},
{
title:"Robin",
mp3 :"Birdsong-Robin.mp3",
lyrics :"Unusually among British birds, both the male and the femaale robins sing"
}
]
function searchIt(str) {
for (i=0; i<tracks.length; i++) {
if(tracks[i].lyrics.indexOf(str) >= 0){
alert(tracks[i].title);
}
}
}
searchIt("Unusually");
因此,在格式化了数组中的语法错误之后,我使用了for循环(我认为你试图使用&#34;对于每个&#34;我还不熟悉)。我遍历了数组,并询问(str)是否匹配&#34;歌词中的任何内容&#34;数组的每个元素,如果是,它将返回0或更大。如果没有,那将是-1。因此,如果它符合我的条件,那么它将返回轨道的标题。
继承了indexOf方法https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
的文档