我想从函数访问一个变量

i want to access a variable from function

这是我的html

    <form id="upload">
        <label for="file">File to upload</label>
        <input type="file" id="file" accept=".json">

        <button>Upload</button>
    </form>
    <div id="map"></div>

这是 javascript 文件

    // Get the form and file field
    let form = document.querySelector('#upload');
    let file = document.querySelector('#file');
    // Listen for submit events
    form.addEventListener('submit', handleSubmit);
    /**
     * Handle submit events
     * @param  {Event} event The event object
     */
    function handleSubmit(event) {

        // Stop the form from reloading the page
        event.preventDefault();
        // If there's no file, do nothing
        if (!file.value.length) return;
        // Create a new FileReader() object
        let reader = new FileReader();
        // Setup the callback event to run when the file is read
        reader.onload = logFile;
        // Read the file
        reader.readAsText(file.files[0]);

    }

    function logFile(event) {
        let str = event.target.result;
        let json = JSON.parse(str);
        console.log('string', str);
        console.log('json', json);
    }
    var map_init = L.map('map', {
        center: [9.0820, 8.6753],
        zoom: 8
    });
    var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map_init);
    L.geoJSON(json).addTo(map)

我想在它的函数之外的第二个函数中使用 json 变量。我正在尝试创建一个文件上传输入,可以轻松地将 json 文件读入 leaflet map

L.geoJSON(json).addTo(map)

需要先保存在函数外, let jsonFile = null;

然后在 logFile 函数中你可以重新赋值: jsonFile = JSON.parse(str);