开发者

How to extract elements of an Array

I have the above data ,

var jsonData = [
    {date:'August 19, 2004',open:100.01,high:104.06,low:95.96,close:100.34,volume:22088000},
    {date:'August 20, 2004',open:101.48,high:109.08,l开发者_JAVA技巧ow:100.50,close:108.31,volume:11377000},
    {date:'August 23, 2004',open:110.76,high:113.48,low:109.05,close:109.40,volume:9090700},
    {date:'August 24, 2004',open:111.24,high:111.60,low:103.57,close:104.87,volume:7599100},
    {date:'August 25, 2004',open:104.96,high:108.00,low:103.88,close:106.00,volume:4565900}
];

I would like to get all the sigle values of the date , i have used this one

for(var i = 0; i<jsonData.length; i++) 
    var date = jsonData[i].date;
date = date.split(' ');
return date; 

But i am getting only the Last Value that is August,25,,2004

How can i get all the values ??


There is a problem with your loop. It only runs once, and even if you removed that, it would keep overwriting the value stored in date

If you want to store all the dates, you need to make it into an array and store the date. I'm not sure what you mean by single values of dates but this structure will solve the problem for you.

var dates = [];
for(var i = 0; i<jsonData.length; i++) {
   var date = jsonData[i].date;
   date = date.split(' '); 
   //do whatever you want with your date. transform.
   dates.push(date); //push the final version of the date you want to store
}
return dates;  //return an array of dates


You are overwriting the date variable in each iteration of your loop. Instead, keep a variable (initialized outside of the loop) and push each date array (generated inside the loop) to it.

dates = [];
for ( idx in jsonData ) {
    dates.push(jsonData[idx].split(' '));
}

// dates is an array of arrays now
// for example: [['August', '19,', '2004'], ...]
return dates;


hi here you define a loop so every value of array is overwrite in date variable so it gives last overwritten values

to extract all value you do not use loop this type you define

you simply write

var date1 = jsonData[0].date; var date2 = jsonData[1].date;


In your loop you are putting all the dates in the same variable, so in each iteration you are overwriting the previous value. Add the dates to an array instead:

var dates = [];
for(var i = 0; i<jsonData.length; i++) {
  dates.push(jsonData[i].date);
}
return dates; 

That returns an array of date strings. If you want to split each date and return an array of array of strings:

var dates = [];
for(var i = 0; i<jsonData.length; i++) {
  dates.push(jsonData[i].date.split(' '));
}
return dates; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜