如何在 JS 中迭代哈希并返回所有匹配结果?
我在一个函数中有以下一段 JS 代码,它响应用户按 Enter 键(未显示)。我关心的代码部分如下所示:
$.each(cityhash,function(key,value){
if(value['city']== user_input) {
$('#city').empty().append(value['city']);
$('#state').empty().append(value['city']);
}
我有以下哈希:
cityhash = [{"address":"07288 Albertha Station","city":"Littelside","state":"Missouri"},{"address":"0615 Mervin Rapid","city":"Tessmouth","state":"South Carolina"},{"address":"779 Elody Lock","city":"Littelside","state":"New Mexico"}]
如您所见,利特尔赛德市在哈希中出现了两次。我的问题是上面的 $.each 函数,只显示 2 个 Littlesides 中的 1 个。我想显示哈希中的所有匹配项,而不仅仅是 1 个匹配项。
如何更正我的代码以返回所有匹配的城市,而不是仅显示一个城市?
预先感谢您
I have the following piece of JS code within a function that responds to the user pressing enter (not displayed). The part of the code I am concerned with is shown:
$.each(cityhash,function(key,value){
if(value['city']== user_input) {
$('#city').empty().append(value['city']);
$('#state').empty().append(value['city']);
}
I have the following hash:
cityhash = [{"address":"07288 Albertha Station","city":"Littelside","state":"Missouri"},{"address":"0615 Mervin Rapid","city":"Tessmouth","state":"South Carolina"},{"address":"779 Elody Lock","city":"Littelside","state":"New Mexico"}]
As you can see, the city of Littelside appears twice in the hash. My problem is the above $.each function, only displays 1 of the 2 Littlesides. I would like to show all matches in the hash, not just 1 match.
How can I correct my code to return all matching cities rather than just showing one city?
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要摆脱empty() 调用。您将在每场比赛中清除#city/#state。
另外,您可能希望将州名称而不是城市名称附加到 #state 元素
You need to get rid of the empty() calls. You are clearing out #city/#state on each match.
Also, you probably want to append the state name and not the city name to the #state element