Возврат информации из массива JS для использования в качестве глобальной переменной - PullRequest
0 голосов
/ 01 ноября 2018

1-й раз публикует здесь, надеясь, что кто-то может мне помочь.

Я все еще изучаю JS и не знаю много о языке, я провел поиск в Google, но не могу найти решение

Заранее извиняюсь, если это очень тупой вопрос или на него уже был дан ответ

Вот код, который выбирает информацию из документа Google Sheet и помещает ее в массив (спасибо @ Z-Bone)

var spreadsheetUrl ='https://spreadsheets.google.com/feeds/cells/1XivObxhVmENcxB8efmnsXQ2srHQCG5gWh2dFYxZ7eLA/1/public/values?alt=json-in-script&callback=doData';
var mainArray =[]

// The callback function the JSONP request will execute to load data from API
function doData(data) {
// Final results will be stored here    
var results = [];

// Get all entries from spreadsheet
var entries = data.feed.entry;

// Set initial previous row, so we can check if the data in the current cell is 
from a new row
var previousRow = 0;

// Iterate all entries in the spreadsheet
for (var i = 0; i < entries.length; i++) {
    // check what was the latest row we added to our result array, then load it 
to local variable
    var latestRow = results[results.length - 1];

    // get current cell
    var cell = entries[i];

    // get text from current cell
    var text = cell.content.$t;

    // get the current row
    var row = cell.gs$cell.row;

    // Determine if the current cell is in the latestRow or is a new row
    if (row > previousRow) {
        // this is a new row, create new array for this row
        var newRow = [];

        // add the cell text to this new row array  
        newRow.push(text);

        // store the new row array in the final results array
        results.push(newRow);

        // Increment the previous row, since we added a new row to the final 
results array
        previousRow++;
    } else {
        // This cell is in an existing row we already added to the results 
array, add text to this existing row
        latestRow.push(text);
    }

}

handleResults(results);
}

// Do what ever you please with the final array
function handleResults(spreadsheetArray) {
console.log(spreadsheetArray);
}

// Create JSONP Request to Google Docs API, then execute the callback function 
doData
$.ajax({
url: spreadsheetUrl,
jsonp: 'doData',
dataType: 'jsonp'
});

Здесь я хотел бы объявить все свои элементы массива как переменные, чтобы я мог использовать любой из них в любой другой функции на сайте в глобальном масштабе или записать его во innerHTML из любой функции

Если объявлять их как переменные не является правильным решением, не стесняйтесь предлагать что-то еще, как я сказал новичку в JS

Заранее благодарим за помощь Stack Overflow Family

1 Ответ

0 голосов
/ 01 ноября 2018

Сохраните переменную, которую вы хотите стать глобальной, как свойство window:

function handleResults(spreadsheetArray) {
    window.spreadsheetArray = spreadsheetArray;
}

Для проверки:

handleResults([1,2,3]);

(function printArray() {
    console.log(window.spreadsheetArray);
})();
...