Dynamically create a two dimensional Javascript Array

后端 未结 7 1775
臣服心动
臣服心动 2020-12-11 22:07

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?

desired array contents:

相关标签:
7条回答
  • 2020-12-11 22:40

    [SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:

    var outterArray = [];
    
    var outterArray = $('.something').map(function() {
    
        // find .somethingElse inside current element
    
        return [$(this).find('.somethingElse').map(function() {
            return $(this).text();
        }).get()]; // return an array of texts ['text1', 'text2','text3']
    
    }).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array
    
    // notice that this alert text1,text2,text3,text4,text5,text6 
    alert(outterArray);​ 
    
    // even when the array is two dimensional as you can do this: 
    alert(outterArray[0]); 
    alert(outterArray[1]);
    

    HTML:

    <div class="something">
        <span class="somethingElse">test1</span>
        <span class="somethingElse">test2</span>        
        <span class="somethingElse">test3</span>           
    </div>
    <div class="something">
        <span class="somethingElse">test4</span>
        <span class="somethingElse">test5</span>        
        <span class="somethingElse">test6</span>           
    </div>
    

    Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/

    0 讨论(0)
提交回复
热议问题