Dynamically create a two dimensional Javascript Array

后端 未结 7 1812
臣服心动
臣服心动 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:

    test1 test2 test3
    test4 test5 test6

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

提交回复
热议问题