简体   繁体   中英

How do I manipulate the data within this array? javascript

Below I have a javascript function that reads a CSV file and interprets the data into an array within the webpage.

document.getElementById('file').onchange = function(){

var file = this.files[0];

var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file

// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
}
        $('#input').append(lines);
};
reader.readAsText(file);
};

$(document).ready(function() {
    example2();

    $('#upload').bind('click', function() {
        example2();
    });
});

function example2() {
    var input = $('#input').val();
    var data = $.csv.toArrays(input);
    var html = generateTable(data);
    $('#result').empty();
    $('#result').html(html);
        console.log(data);
}

I now need to pull out and manipulate the data within the array but any time I try to reference the array data, it says it cannot find it.

You're appending lines to some element in the DOM: $('#input')

Why not declare a variable outside of your functions:

var someArray = [];

Then use to push to that instead or in parallel with adding to "input" element, so (you have a typo in the for loop, you append all lines instead of just current line):

for (var i = 0; i < lines.length; i++) {
    $('#input').append(lines[i]);
    someArray.push(lines[i]);
};

After this your "someArray" is available everywhere in the page scope.

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