【问题标题】:How do I compare a JSON object with a string in Javascript如何将 JSON 对象与 Javascript 中的字符串进行比较
【发布时间】:2013-04-28 23:04:12
【问题描述】:

我正在为http://myttc.ca 开发此网站布局。我成功地检索了大部分数据并将其显示在页面上。

但是,当我必须过滤搜索以仅查找只有 Subway 的站点名称时,我遇到了错误。这是 JSON 页面,http://myttc.ca/finch_station.json。在这里,当我尝试仅访问路线名称为 Yonge-University-Spadina Subway 的站点时,我收到一条错误消息,指出 Uncaught TypeError: Cannot call method 'equals' of undefined。我还尝试简单地放置=== 运算符。也许我必须反序列化或其他什么,但在通过互联网解决这个问题后,现在完全无能为力了。我是 javaScript 的新手,我想也许我在这里遗漏了一些东西。到目前为止,这是我的代码:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
      $(document).ready(function(){
        // retrieving the data.
        $.getJSON("http://myttc.ca/finch_station.json?callback=?", function(data){
          //Storing the string in variable.   
          var subway="Yonge-University-Spadina Subway";

          console.log(data);
          //Displaying the station name first in a div called "stations" in the body.
          $("#stations").append('Station: ' + data.name + '<br/>');

          //Iterating through the stops array to display each stop name 
          $.each(data.stops, function(i,stopz){

          $("#stations").append('&nbsp;&nbsp;Stop: ' + stopz.name + '<br/>');
          //This is my problem area.Not able to compare the routes.name to the string.   
          if(stopz.routes.name === subway) {
            $.each(stopz.routes, function(i,routez) {
              //Displaying the Departure time and shape of the stops.
              $.each(routez.stop_times, function(i,timez) {
                $("#stations").append('&nbsp;&nbsp;&nbsp;&nbsp;Departure-time: ' + timez.departure_time + ' || Shape: ' + timez.shape + '<br/>');  
              });
            });
            }
          });
         });
       });
     </script>

 </head>
 <body>

 <div id="stations">
 </div>
 </body>
 </html>

谢谢。

【问题讨论】:

  • 使用浏览器的调试器——Chrome 的开发者工具、IE 的开发者工具、Firefox 的 Firebug 插件(全部按 F12 启动)。未定义意味着您正在使用未声明的变量。找出那是什么。
  • ..通过快速浏览,我发现“name”属性属于“routes”数组;尝试 $.each 那个。

标签: javascript json string object equals


【解决方案1】:

鉴于您的止损数据格式:

{"routes":[],"name":"Finch Station GO Hallway","uri":"finch_station_go_hallway","agency":"Toronto Transit Commission"}

您对stopz.routes.name 的引用无效。我想你的意思是stopz.name。所以你的代码应该是这样的:

            if(stopz.name === subway)
            {
                $.each(stopz.routes, function(i,routez){
                    // ... etc ...
                });
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多