search

Home  >  Q&A  >  body text

javascript - Declare an object outside a function and then assign a value within the function. As a result, the assigned value cannot be obtained outside the function.


As shown in the picture, you can see the value when expanded, but the value is not actually in the object

if (typeof require !== 'undefined') var XLSX = require('xlsx');

function to_json(workbook) {
    var result = {};
    workbook.SheetNames.forEach(function(sheetName) {
        var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        if (roa.length > 0) {
            result[sheetName] = roa;
        }
    });
    return result;
}
export function handleFile(e) {
    var files = e.target.files;
    var i, f;
    var testTest = {};
    for (i = 0; i != files.length; ++i) {
        f = files[i];
        var reader = new FileReader();
        var name = f.name;
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook;
            /* if binary string, read with type 'binary' */
            workbook = XLSX.read(data, {
                type: 'binary'
            });
            let excelData = to_json(workbook);
            testTest.data = excelData;
        };
        reader.readAsBinaryString(f);
    }
    console.log(testTest)
    return testTest

}
迷茫迷茫2832 days ago434

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-19 10:21:52

    When chrome's console prints an object, the view value is obtained in detail when you click to expand it. The whole process:

    1. Empty object declaration

    2. Execute console, chrome prints the object, and passes the reference of the object

    3. FileReader is completed, assign data to the object

    4. In the console, click to expand the value and get the detailed value of the object through the object reference

    You can see the icon of the screenshotObject {} [i]这里有个[i], with the corresponding object console description:

    value below was evaluated just now

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:21:52

    The question is, when does your reader.onload run?


    Also, I still don’t understand, why not just copy and paste the code? ? ? Why take a screenshot?

    reply
    0
  • Cancelreply