Splitting a string in javascript and storing in multidimentional array
I have a string
string s='2011/01/03 00:00:00,14.00|2011/01/03 00:00:00,14.50|2011/01/03 00:00:00",15.00|2011/01/02 00:00:00,12.00|';
I want to split the string first by '|' , which i can do by using
var ds=[];
ds=s.split('|');
i further want to split them by ',' and store in an array
The question is how do i store in a multidimention array so the output looks similar to this
da[0]={'2011/01/03 00:00:00开发者_运维问答',14.00}
da[1]={'2011/01/03 00:00:00',14.50}
.
.
.
Thanks Prady
var ds = s.split('|');
for( var i = 0, len = ds.length; i < len; i++ ) {
if( ds[i] )
ds[i] = ds[i].split(',');
}
Result looks like:
[
['2011/01/03 00:00:00','14.00'],
['2011/01/03 00:00:00','14.50'],
['2011/01/03 00:00:00','15.00'],
['2011/01/02 00:00:00','12.00'],
''
]
var s='2011/01/03 00:00:00,14.00|2011/01/03 00:00:00,14.50|2011/01/03 00:00:00,15.00|2011/01/02 00:00:00,12.00';
var pieces = s.split('|');
for (var i=0,len=pieces.length;i<len;++i){
var pair = pieces[i].split(',');
pieces[i] = {};
pieces[i][pair[0]] = pair[1]*1; //*1 to convert from string to number
}
console.log(pieces);
// [
// {'2011/01/03 00:00:00':14.00},
// {'2011/01/03 00:00:00':14.50},
// {'2011/01/03 00:00:00':15.00},
// {'2011/01/02 00:00:00':12.00},
// ]
This is assuming, based on your pseudo-JS syntax using curly braces, that you really meant an array of objects instead of a multi-dimensional array. If you want a single object hashing 'time-as-string' to values, you might do:
var pieces = s.split('|');
var values = {};
for (var i=0,len=pieces.length;i<len;++i){
var pair = pieces[i].split(',');
values[pair[0]] = pair[1]*1;
}
console.log(values);
// {
// '2011/01/03 00:00:00': 14.00,
// '2011/01/03 00:00:00': 14.50,
// '2011/01/03 00:00:00': 15.00,
// '2011/01/02 00:00:00': 12.00,
// }
This would allow you to find the value for any given day in constant time, without traversing the array of values.
精彩评论