if语句破坏.push方法

时间:2012-02-25 15:08:50

标签: javascript if-statement push each

所以我循环遍历一组JSON数组,然后循环遍历每个单独的数组。

如果我删除了两个if语句,它将遍历两个数据集并附加' target'使用这两个数据'设置,但就像它现在一样,它只会通过第一个循环追加items.join。

案例的内容首先是if循环,认为这很重要,但不是。

奇怪的是,consoleOut(比如console.log)确实打印了我的东西,所以它确实循环遍历JSON集中的两个数组。

    $.each(data, function(keys, vals)
    {

    var items = [];


     $.each(data[keys], function(key, val) 
     {

        var currString = JSON.stringify(val);
        switch (key)
        {
        case "ID":              
            consoleOut("ID: "+currString+" loaded");
        break;                                      

        case "parentIDs":

            consoleOut("parentIDs: "+currString);
        break;
        case "UID":
            consoleOut("UID: "+currString);
            UID = unquote(currString);
        break;
        case "title":
            consoleOut("Title: "+currString);
            items.push('<H1 class="' + key + '">' + unquote(currString) + '</H1>');
        break;
        case "img":
            consoleOut("IMG: "+currString);

            if ($(currString).val() !== '')
            {
            items.push('<IMG class="' + key + '" src='+currString+'></IMG>');               
            };
        break;
        case "text":
            consoleOut("TXT: "+currString);

            if ($(currString).val() !== '')
            {
            items.push('<P class="' + key + '">'+currString+'</P>');

            };
        break;
        }
      });
      consoleOut("---------");

      $('<DIV/>', {
        'id': UID,
        html: items.join('')
      }).appendTo(target);
    } 
) 

我想知道if语句如何破坏我对主要&#39;项目的追加。阵列..

(当我没有在开始时对val进行字符串化时它会循环,但那是因为if语句是真的,但是当假的时候停止工作..所以也许它会更好修改我的if语句,但是我仍然对.push如何停止工作感到困惑?)

2 个答案:

答案 0 :(得分:1)

$(currString).val() 

它说你正在创建一个元素并查看该元素的value属性。那是你真正想要的吗?我不认为图像或文字有价值。

我认为你会想要使用length或html()

[编辑]看着你的对象,你只想检查一下currString的长度

if( currString && currString.length>0 ) {

答案 1 :(得分:0)

这不是JSON,它是一个数组。

[{"ID":"1",
  "parentIDs":null,
  "UID":"home",
  "title":"Home",
  "text":"<3 here",
  "img":"/favicon.ico",
  "url":"home",
  "cat_id":"1",
  "view_id":"",
  "css_id":null}‌​,
 {"ID":"4",
  "parentIDs":"home",
  "UID":"home_info",
  "title":"Info about Home",
  "text":"Info about Home",
  "img":"",
  "url":"",
  "cat_id":"",
  "view_id":"",
  "css_id":null}
]

你确定你的输入看起来不像这样(即JSON)吗?

{ "data" : [{"ID":"1",
             "parentIDs":null,
             "UID":"home",
             "title":"Home",
             "text":"<3 here",
             "img":"/favicon.ico",
             "url":"home",
             "cat_id":"1",
             "view_id":"",
             "css_id":null}‌​,
            {"ID":"4",
             "parentIDs":"home",
             "UID":"home_info",
             "title":"Info about Home",
             "text":"Info about Home",
             "img":"",
             "url":"",
             "cat_id":"",
             "view_id":"",
             "css_id":null}
           ] }
相关问题