简体   繁体   中英

Add array to array in javascript?

How do I add an array to array with variables & functions?

var ranges = new Array();
fulldate='2012/06/11:2012/10/23|2012/03/11:2012/05/23'.split('|');

for(var i=0; i<fulldate.length; i++) {
    adate=fulldate[i].toString().split(':');

    startdate=adate[0].toString().split('/');
    enddate=adate[1].toString().split('/');

    //***This area****************************
    ranges.push = ({ start: new Date(startdate[0],startdate[1]-1,startdate[2]), end: new Date(enddate[0],enddate[1]-1,enddate[2]) });
    //***This area****************************
}

push是一种方法,您必须像这样使用它:

ranges.push({ start: new Date(startdate[0],startdate[1]-1,startdate[2]), end: new Date(enddate[0],enddate[1]-1,enddate[2]) });

To be persnickety, you aren't really trying to add an array to another. For that you can just use array.concat() :

var cArray = aArray.concat(bArray).

It looks like you want to transform one array into another. You could use array.map() :

var fulldate='2012/06/11:2012/10/23|2012/03/11:2012/05/23'.split('|');
var ranges = fulldate.map(function(x) {
    var adate=x.toString().split(':');
    var startdate=adate[0].toString().split('/');
    var enddate=adate[1].toString().split('/');
    return { 
        start: new Date(startdate[0],startdate[1]-1,startdate[2]),
        end: new Date(enddate[0],enddate[1]-1,enddate[2])
    };
});

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