gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:21:01 26 4
gpt4 key购买 nike

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

我还在学习 JS,对这门语言了解不多,我做了一些谷歌搜索,但找不到解决方案

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

这是从 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);
})();

关于javascript - 从 JS 数组返回信息以用作全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53104321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com