Return 来自 JS 数组的信息用作全局变量

Return info from JS array to use as a variable globally

第一次在这里发帖,希望有人能帮助我。

我还在学习 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 家族的帮助

将您希望成为全局变量的变量存储为 window 的 属性:

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

测试:

handleResults([1,2,3]);

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