I have a problem with populating a JavaScript array with a function...
I have some charting software that uses JavaScript. I can input my own values into an array directly to create my desired chart like so:
var data_array=[[0,170],[0,185],[0,179]]
The first value in the array corresponds to sample number (e,g, 0) and the second value corresponds to height (eg 170, 185 etc). This works but I will eventually have a huge list of thousands of values. The height values will be stored in text files. There will be a different file for each sample. The text file will contain a simply list of values separated by lines.
What I need my program to do is open a text file and extract the values and then append them to the data array. So far I have this:
$.get('sample0.txt', function(data, data_array){
var lines=data.split('\n');
for (var i=0; i<lines.length-1;i++){
var item=lines[i];
data_array.push([0,item]);
}
return data_array
}
This doesn't work, although I know it is correctly extracting the values from the text file. I'm not worried about sample number as I can set this for each file. My problem is how to populate the array and make that array exist outside of the function.
I normally code in PHP and I apologize that my knowledge of JavaScript is very basic!
// set this somewhere outside of the $.get callback.
// no need to pass it in as it will be available in that scope.
var data_array = [];
$.get('sample0.txt', function(data) {
var lines=data.split('\n');
for (var i=0; i<lines.length;i++){
var item=lines[i];
data_array.push([0,item]); // modify data_array here
}
// no need to return it
});
Here's a very reduced test: http://jsfiddle.net/4GMMd/
Also note no -1
after lines.length
in your for loop, unless your files end with a blank line that you don't want to read.
If I understand your question correctly, you just need to declare the data_array outside the scope of your request function. Plus, your loop is incorrect. It should be i<lines.length
not lines.length-1
unless you intend to leave out the last line.
var data_array = [];
$.get('sample0.txt', function(data){
var lines=data.split('\n');
for (var i=0; i<lines.length;i++){
var item=lines[i];
data_array.push([0,item]);
}
}
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.