简体   繁体   中英

Connecting multiple arrays in javascript not concat

I'm looping through JSON data to pull out dates and placing them into an array. The following code is an example of my code inside the loop.

// get the JSON data
var foo = "2013-03-28";

// split foo into an array
var bar = foo.split('-');        // Output ["2013", "03", "08"] 

// putting array in necessary format
for (a in bar) {
    bar[a] = parseInt(arr[a]);   // Output [2013, 3, 8] 
}

Now that I have my array the way I need it, the next time it loops I want to add to a bigger array such as follows

// Trying to add each new array to a bigger array
baz += bar

// Sample output I'm looking for
baz = [ [2013, 3, 8], [2013, 2, 12], [2013, 1, 22], ... ]

Help would be greatly appreciated

使用push将元素添加到数组的末尾:

baz.push(bar);

Your var foo = "2013"-"03"-"28" is not a string .. To add an element in a array , use push method..

var foo = "2013-03-28";// This is a string 

// split foo into an array
var bar = foo.split('-');        // Output ["2013", "03", "08"] 

baz.push(bar);

It also does the same

Example :

var array = [];
for(var i=0;i<5;i++)
{
    var a = [2012,i,25];
    array.push(a);
    alert(array);
}

Running Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM