从JS数组返回信息以全局用作变量

时间:2018-11-01 15:26:23

标签: javascript arrays ajax google-sheets jsonp

第一次在这里发布,希望有人可以帮助我。

我仍在学习JS,对语言不了解很多,我已经做了一些Google搜索,但是找不到解决方法

如果这是一个非常愚蠢的问题或在此之前已经回答过,请提前道歉

这是从Google表格文档中获取信息并将其放入数组中的代码(感谢@ 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系列

1 个答案:

答案 0 :(得分:0)

将要成为全局变量的变量存储为window的属性:

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

要测试:

handleResults([1,2,3]);

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