根据值将数组拆分为其他数组

时间:2012-04-03 15:59:18

标签: javascript arrays

大家好,我有一个看起来像这样的数据(它包含列表编号和品牌名称):

["1_Sophie_Gray", "2_Atlantic_Bay", "2_Trait", "3_Tammy", "3_Flipback", "3_Duck_Dodge", "3_Bambini", "4_Bellisima"]

我需要做的是将这些分开并为每个列表创建一个ul(1个是女装,2个男装,3个童装等)。我虽然最好的方法是循环遍历这个数组,并根据列表号将值分成不同的数组,例如。

["1_Sophie_Gray"]

["2_Atlantic_Bay", "2_Trait"]

["3_Tammy", "3_Flipback", "3_Duck_Dodge"]

我想这样做的原因是为每个新阵列构建一个单独的图标列表。所以最终我会以此结束:

<div class="store_brands">
<p id="brand_intro">
    Brands and departments available in this store:
</p>
<h4>list 1</h4>
<ul>
    <li>
        <img src="/images/v3/brand_logos/wallis.gif" alt="list 1 brands" />
    </li>
</ul>
<h4>list 2</h4>
<ul>
    <li>
        <img src="/images/v3/brand_logos/atlantic_bay.gif" alt="list 2 brands" />
    </li>
    <li>
        <img src="/images/v3/brand_logos/trait.gif" alt="list 2 brands" />
    </li>
</ul>
<h4>list 3</h4>
<ul>
    <li>
        <img src="/images/v3/brand_logos/tammy.gif" alt="list 3 brands" />
    </li>
    <li>
        <img src="/images/v3/brand_logos/flipback.gif" alt="list 3 brands" />
    </li>
    <li>
        <img src="/images/v3/brand_logos/duck_dodge.gif" alt="list 3 brands" />
    </li>
</ul>

这是我的代码:

function inStoreBrands (storeData) {

var brandsArr = [],
    listNum,
    fileName,
    brandImgsPath = "/images/v3/brand_logos/",      
    brandList = '<div class="store_brands"><p id="brand_intro">Brands and departments available in this store:</p>',
    brandResults = storeData.brands,
    brands = brandResults.split(", "),
    listCount = 1,
    titleText = "list 1";

        for (var i=0; i<brands.length; i++) {
            listNum = brands[i].split(/_(.+)/)[0];
            listNum = parseInt(listNum);

            fileName = brands[i].split(/_(.+)/)[1];
            fileName = fileName.toString().toLowerCase();

            function addToArray () {
                brandsArr.push(brandImgsPath + fileName + '.gif');
            }

            if(listNum !== listCount){
                buildBrandList(brandsArr, titleText);
                titleText = "list " + listNum;
                addToArray();
            } else {
                addToArray();
            }
        }

function buildBrandList(brandsArr, titleText) {
    brandList += '<h4>'+titleText+'</h4>';
    brandList += '<ul>';
    for (i=0; i < brandsArr.length; i++) {
        brandList += '<li><img src="'+brandsArr[i]+'" alt="'+titleText+' brands" /></li>';
    }
    brandList += '</ul>';
    brandsArr = [];
    listCount++;
}

brandList += '</div>';      
return brandList;               
};

我知道逻辑是非常有缺陷的,因此它不起作用的原因。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您没有发布storeData的确切数据以及如何构建它 - 所以我做了一些假设:see the demo

答案 1 :(得分:1)

简单的设计更改可能会帮助您。请考虑更改您创建品牌阵列的格式。例如,不要存储1_Sophie_Gray,而应考虑1_Sophie-Gray。

var arr1;
var arr2;
//etc

for(i=0;i<brands.length - 1; i++){ //So we've split 1_Sophie-Gray from everything else
   var tmpArr = brands[i].split('_');
   if(tmpArr[0] == 1){             //parse to the correct array
      arr1.push("brands[i]");      //push into the appropriate array
   } else if(tmpArr[0] == 2) {
      arr2.push("brands[i]");
   }
}

请记住,这是伪造的代码。希望有所帮助!

-sf

编辑:在评论中回答El Guapo的问题。是的,您可以动态创建arr变量,但是您必须通过代码隐藏方面的一些工作来完成。示例背后的所有代码都在VB.Net中。

如果您希望在页面加载时触发此功能。您可以使用Page.ClientScript.RegisterClientScriptBlock方法在Page_Load函数中构建和注册它。 Page_Load()

中的示例
Protected Overrides Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
     If Not ScriptManager1.IsInAsyncPostBack Then
      MyBase.Page_Load(sender, e)
      'Do whatever else you need to do on Page Load

      Page.Form.DefaultButton = btnSubmit.UniqueID
      Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), Guid.NewGuid().ToString(),createjs())

End Sub

Public Function createjs() As String
   Dim str As String = ""
   str = "<script type='text/javascript' language='javascript'>function ClickSubmit(){var btn = '" & btnSubmit.ClientID & "'; btn = getElementSomehow(btn); btn.click()};" & _
   " <all your javascript> " & _
   " //Im using & _ to make things more readable once the js gets created" & _
   " </script>"
   return str
End Function

从后面的代码创建javascript允许您将数组传递给通常不可用的客户端。让我们采取上面的人为举例,并更接近你想做的事情。 Say arr是你在其他地方得到的变量,它的定义如下:

arr = ""1_Sophie_Gray", "2_Atlantic_Bay", "2_Trait", "3_Tammy", "3_Flipback", "3_Duck_Dodge", "3_Bambini", "4_Bellisima""

请注意,您可以完全从.vb代码添加,删除,修改此数组。然后,一旦它在你想要的地方。您可以将它抛给您的代码,该函数负责创建客户端javascript。

Public Function ModifyJS(ByVal PassedArr As String) As String
   Dim str As String = ""
   str = "<script type='text/javascript' language='javascript'>function ClickSubmit(){var btn = '" & btnSubmit.ClientID & "'; btn = getElementSomehow(btn); btn.click()};" & _
   " <all your javascript> " & _
   " var JSarr = [" & PassedArr & "]; " & _
   " //Im using & _ to make things more readable once the js gets created" & _
   " </script>"
   return str
End Function

然后......到达这里并不是一个巨大的飞跃:

Public Function ModifyJS(ByVal PassedArr As String, ByVal NoArrays As Integer) As String
   Dim str As String = ""
   str = "<script type='text/javascript' language='javascript'>function ClickSubmit(){var btn = '" & btnSubmit.ClientID & "'; btn = getElementSomehow(btn); btn.click()};" & _
   " <all your javascript> " & _
   " var JSarr = [" & PassedArr & "]; " & _
   For i As Integer = 0 To NoArrays
      str &= " var arr" & i & "=[];"
   Next
   " //Im using & _ to make things more readable once the js gets created" & _
   " </script>"
   return str
End Function

希望有助于兄弟!

-sf