Javascript Arrays - Справка по объединению нескольких массивов - PullRequest
0 голосов
/ 16 сентября 2010

Интересно, может ли кто-нибудь помочь мне решить следующую проблему, с которой я столкнулся в своем проекте JS?

У меня есть информация о продукте, полученном из 3 разных списков JSP:

  • A Сведения о продукте
  • A Рейтинг продуктов
  • A Розничные продавцы продуктов

То, что я пытаюсь сделать, это пройти через три JSPсписки, извлекая соответствующую информацию для каждого из продуктов, а затем создайте объект Javascript, в котором хранится вся информация о продукте.

После создания мне нужно перебрать этот объект Javascript и отобразить информацию о каждом продукте на экране.- может быть одновременно 10, 20 и т. д. продуктов.

У меня возникли проблемы с тем, что при создании объекта 'mainResults' (см. мой фрагмент кода ниже), хотя этозаполнено правильно, сначала я получаю пустой массив, а затем массивы продуктов.

Ниже приведен скриншот с Firebug, который показывает выдержку из объекта javascript 'mainResults' - это моя проблема с пустыми массивами:

текст ссылки

Это вызывает у меня проблемыкогда я пытаюсь перебрать «mainResults», используя его свойство length, поскольку оно всегда возвращается как «0».

Я уверен, что есть лучший способ достичь того, что мне нужно сделать, но после долгих поискови играя с ООП, я все еще не могу найти хорошее решение.

Есть пара важных вещей, которые мне нужно добавить:

  • Я никогда не буду точно знать, сколько продуктовбудет.
  • Каждый продукт имеет до 3 оценок.
  • Я никогда не буду точно знать, сколько розничных продавцов у продукта.
  • Мне нужен доступ к продукту,его рейтинги и розничные продавцы по индексу

Я разместил соответствующие части своего кода ниже - я действительно надеюсь, что кто-то может указать мне правильное направление:)

Большое спасибо заранее

Джим

<body onLoad="populate()">
<jsp:useBean id="products" scope="request" class="com.sslpost.mpr.pricerunner.Products" />

    <% if(request.getAttribute("products") != null) 
    products = (Products)request.getAttribute("products"); %>

<script language="JavaScript" type="text/javascript">
    function populate(){
        <% if(products != null) { %>

        //Access Products from JSP Product Class        

        <% for (int i=0; i<products.productsList.size(); i++) {
        Product currProd = products.productsList.get(i);

        //Check Product Id is Not Empty and Handle Accordingly
        String prodId = "";
        if(products.productsList.get(i).id != 0)
            { prodId = Integer.toString(products.productsList.get(i).id); }
        else{ prodId = Integer.toString(0); }

        //Check Product Name is Not Empty and Handle Accordingly
        String prodName = "";
        if(products.productsList.get(i).name != null)
            prodName = products.productsList.get(i).name;

        //Check Product Manufacturer is Not Empty and Handle Accordingly
        String prodManufacturer = "";
        if(products.productsList.get(i).manufacturer != null)
            prodManufacturer = products.productsList.get(i).manufacturer;

        //Check Product Description is Not Empty and Handle Accordingly
        String prodDescription = "";
        if(products.productsList.get(i).description != null)
            prodDescription = products.productsList.get(i).description;

        //Check Product Retailer is Not Empty and Handle Accordingly
        String prodRetailer = "";
        if(products.productsList.get(i).numberOfRetailers != 0)
            { prodRetailer = Integer.toString(products.productsList.get(i).numberOfRetailers); }
        else{ prodRetailer = Integer.toString(0); }

        //Check Product Logo + Height and Width Attributes are Not Empty and Handle Accordingly
        String prodLogo = "";
        if(products.productsList.get(i).imageUrl != null && products.productsList.get(i).imageUrl.imageUrl != null)
            { prodLogo = products.productsList.get(i).imageUrl.imageUrl; }
        else{ prodLogo = "images/image_remove.png"; }    

        String prodLogoHeight = "";
        if(products.productsList.get(i).imageUrl != null && products.productsList.get(i).imageUrl.height != 0)
            { prodLogoHeight = Integer.toString(products.productsList.get(i).imageUrl.height); }
        else{ prodLogoHeight = Integer.toString(0); }

        String prodLogoWidth = "";
        if(products.productsList.get(i).imageUrl != null && products.productsList.get(i).imageUrl.width != 0)
            { prodLogoWidth = Integer.toString(products.productsList.get(i).imageUrl.width); }
        else{ prodLogoWidth = Integer.toString(0); }

        //Check Product Prices + Currency Attributes are Not Empty and Handle Accordingly
        String lowPriceAmount = "";
        if(products.productsList.get(i).lowestPrice != null && products.productsList.get(i).lowestPrice.amount != null)
            lowPriceAmount = products.productsList.get(i).lowestPrice.amount;

        String lowPriceCurrency = "";
        if(products.productsList.get(i).lowestPrice != null && products.productsList.get(i).lowestPrice.currency != null)
            lowPriceCurrency = products.productsList.get(i).lowestPrice.currency;

        String highPriceAmount = "";
        if(products.productsList.get(i).highestPrice != null && products.productsList.get(i).highestPrice.amount != null)
            highPriceAmount = products.productsList.get(i).highestPrice.amount;

        String highPriceCurrency = "";
        if(products.productsList.get(i).highestPrice != null && products.productsList.get(i).highestPrice.currency != null)
            highPriceCurrency = products.productsList.get(i).highestPrice.currency;           
        %>

        productResults(<%= i %>,
                        "<%= prodId %>",
                        "<%= prodName %>",
                        "<%= prodManufacturer %>",
                        "<%= prodDescription %>",
                        "<%= prodRetailer %>",
                        "<%= prodLogo %>",
                        "<%= prodLogoHeight %>",
                        "<%= prodLogoWidth %>",
                        "<%= lowPriceAmount %>",
                        "<%= lowPriceCurrency %>",
                        "<%= highPriceAmount %>",
                        "<%= highPriceCurrency %>"
                        );

        //Access Ratings from Ratings List in JSP Product Class

        <% for(int j=0; j<currProd.ratingList.size(); j++) { 

        //Check Product Rating Type is Not Empty and Handle Accordingly
        String prodRatType = "";
        if(currProd.ratingList.get(j).type != null)
            { prodRatType = currProd.ratingList.get(j).type; }
        else{ prodRatType = "no rating"; }    

        //Check Product Rating Average Value is Not Empty and Handle Accordingly
        String prodRatAvg = "";
        if(currProd.ratingList.get(j).average != null)
            { prodRatAvg = currProd.ratingList.get(j).average; }
        else{ prodRatAvg = Integer.toString(0); }

        //Check Number of Product Ratings Value is Not Empty and Handle Accordingly
        String prodRatNum = "";
        if(currProd.ratingList.get(j).numberRatings != null)
            { prodRatNum = currProd.ratingList.get(j).numberRatings; }
        else{ prodRatNum = Integer.toString(0); }

        %>

        ratingResults(<%= j %>,
                      <%= i %>,
                      "<%= prodRatType %>",
                      "<%= prodRatAvg %>",
                      "<%= prodRatNum %>"
                      );                
           <% } %>

        //Access Retailers from Retailer List in JSP Product Class

        <% for(int x=0; x<currProd.retailerList.size(); x++) {

        //Check Retiailer Logo is Not Empty and Handle Accordingly
        String retailLogo = "";
        if(currProd.retailerList.get(k).logo != null && currProd.retailerList.get(k).logo.imageUrl != null)
            retailLogo = currProd.retailerList.get(k).logo.imageUrl;

        //Check Retailer Product Prices + Currency Attributes are Not Empty and Handle Accordingly
        String minShipPrice = "";
        if(currProd.retailerList.get(k).minPriceWithShipping != null && currProd.retailerList.get(k).minPriceWithShipping.amount != null)
            minShipPrice = currProd.retailerList.get(k).minPriceWithShipping.amount;

        String minShipCurrency = "";
        if(currProd.retailerList.get(k).minPriceWithShipping != null && currProd.retailerList.get(k).minPriceWithShipping.currency != null)
            minShipCurrency = currProd.retailerList.get(k).minPriceWithShipping.currency;

        String maxShipPrice = "";
        if(currProd.retailerList.get(k).maxPriceWithShipping != null && currProd.retailerList.get(k).maxPriceWithShipping.amount != null)
            maxShipPrice = currProd.retailerList.get(k).maxPriceWithShipping.amount;

        String maxShipCurrency = "";
        if(currProd.retailerList.get(k).maxPriceWithShipping != null && currProd.retailerList.get(k).maxPriceWithShipping.currency != null)
            maxShipCurrency = currProd.retailerList.get(k).maxPriceWithShipping.currency;

        %>

        retailerResults(<%= k %>
                        <%= i %>,
                        "<%= currProd.retailerList.get(k).id %>",
                        "<%= currProd.retailerList.get(k).name %>",
                        "<%= currProd.retailerList.get(k).link %>",
                        "<%= retailLogo %>",
                        "<%= currProd.retailerList.get(k).leadTime %>",
                        "<%= currProd.retailerList.get(k).stockInfo %>",
                        "<%= currProd.retailerList.get(k).price.amount %>",
                        "<%= currProd.retailerList.get(k).price.currency %>",
                        "<%= currProd.retailerList.get(k).sourceType %>",
                        "<%= currProd.retailerList.get(k).sourceDate %>",
                        "<%= minShipPrice %>",
                        "<%= minShipCurrency%>",
                        "<%= maxShipPrice %>",
                        "<%= maxShipCurrency %>"
                        );
        <% } %>
        <% } %>
        <% } %>
        }
</script>
<script language="JavaScript" type="text/javascript">
    var mainResults = [];

    function productResults(pnum, pid, pname, pmanu, pdesc, pretail, plogo, plogoh, plogow, plowamt, plowcur, phghamt, phghcur)
    {
        var product = [];

        product.count = pnum;
        product.id = pid;
        product.name = pname;
        product.manufacturer = pmanu;
        product.description = pdesc;
        product.numretailer = pretail;
        product.logo = plogo;
        product.logoh = plogoh;
        product.logow = plogow;
        product.lowpriceamt = plowamt;
        product.lowpricecur = plowcur;
        product.highpriceamt = phghamt;
        product.highpricecur = phghcur;
        product.ratings = [];
        product.retailers = [];
        mainResults[pnum] = product;
    }

    function ratingResults(ratnum, pnum, rtgtype, rtgavg, rtgnum)
    {
        var ratings = [];

        ratings.count = ratnum;
        ratings.type = rtgtype;
        ratings.average = rtgavg;
        ratings.number = rtgnum;
        mainResults[pnum].ratings[ratnum] = ratings;
    }

    function retailerResults(retnum, pnum, rid, rname, rlink, rlogo, rtime, rstock, ramt, rcur, rstype, rsdate, rminamt, rmincur, rmaxamt, rmaxcur)
    {
        var retailers = [];

        retailers.count = retnum;
        retailers.id = rid;
        retailers.name = rname;
        retailers.purchaselink = rlink;
        retailers.logo = rlogo;
        retailers.leadtime = rtime;
        retailers.stock = rstock;
        retailers.priceamt = ramt;
        retailers.pricecur = rcur;
        retailers.sourcetype = rstype;
        retailers.sourcedate = rsdate;
        retailers.shipminprice = rminamt;
        retailers.shipmincur = rmincur;
        retailers.shipmaxprice = rmaxamt;
        retailers.shipmaxcur = rmaxcur;
        mainresults[pnum].retailers[retnum] = retailers;
    }
</script>

1 Ответ

1 голос
/ 16 сентября 2010

Генерация кода с помощью JSP - идея Бааада ... И это определенно худшее поколение кода, которое я когда-либо видел. Тем не менее ... давайте посмотрим, сможем ли мы исправить ваш беспорядок ...

Во-первых, все эти функции не имеют смысла, вы выводите данные в jsp без разбора, функции на самом деле только снижают производительность. Так что лучше сразу отобразить нужный массив (mainResults).

<% if(products != null) { %>

   var mainResults = [
      <% for (int i=0; i<products.productsList.size(); i++) {
         Product currProd = products.productsList.get(i);
      %>

         {
            count : "<%= i %>",
            id : "<%= prodId %>",
            name : "<%= prodName %>",
            manufacturer : "<%= prodManufacturer %>",
            description : "<%= prodDescription %>",
            numretailer : "<%= prodRetailer %>",
            logo : "<%= prodLogo %>",
            logoh : "<%= prodLogoHeight %>",
            logow : "<%= prodLogoWidth %>",
            lowpriceamt : "<%= lowPriceAmount %>",
            lowpricecur : "<%= lowPriceCurrency %>",
            highpriceamt : "<%= highPriceAmount %>",
            highpricecur : "<%= highPriceCurrency %>",
            ratings : [
               <% for(int j=0; j<currProd.ratingList.size(); j++) { %>
                  {
                     count : "<%= j %>",
                     type : "<%= prodRatType %>",
                     average : "<%= prodRatAvg %>",
                     number : "<%= prodRatNum %>"
                  }
               <% if(j < (currProd.ratingList.size() - 1)) { %>
               ,
               <% } %>

               <% } %>
            ],
            retailers : [
               <% for(int x=0; x<currProd.retailerList.size(); x++) { %>
                  {
                     retailers.count : "<%= x %>",
                     id : "<%= currProd.retailerList.get(k).id %>",
                     name : "<%= currProd.retailerList.get(k).name %>",
                     purchaselink : "<%= currProd.retailerList.get(k).link %>",
                     logo : "<%= retailLogo %>",
                     leadtime : "<%= currProd.retailerList.get(k).leadTime %>",
                     stock : "<%= currProd.retailerList.get(k).stockInfo %>",
                     priceamt : "<%= currProd.retailerList.get(k).price.amount %>",
                     pricecur : "<%= currProd.retailerList.get(k).price.currency %>",
                     sourcetype : "<%= currProd.retailerList.get(k).sourceType %>",
                     sourcedate : "<%= currProd.retailerList.get(k).sourceDate %>",
                     shipminprice : "<%= minShipPrice %>",
                     shipmincur : "<%= minShipCurrency%>",
                     shipmaxprice : "<%= maxShipPrice %>",
                     shipmaxcur : "<%= maxShipCurrency %>"
                  }

                  <% if(x < (currProd.retailerList.size() - 1)) { %>
                  ,
                  <% } %>

               <% } %>
            ]
         }

         <% if(i < (products.productsList.size() - 1)) { %>
         ,
         <% } %>

      <% } %>
   ];

<% } %>

Я мог бы сделать несколько опечаток, это было много работы, чтобы исправить ... Но это немного лучше настройки.

Но, ради бога, посмотрите, как создать JSON с Java и создать свою модель на Java, а затем проанализировать JSON.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...