如何在函数外部填充数组?
How can I keep an array filled outside of a function?
此问题是寻找 解决方案的一部分。但是,我想知道是否有办法使用函数来填充数组。根据下面的测试代码,似乎数组在函数后自动清空。我希望有一个函数可以重复填充数组,另一个函数可以触发将结果 array.Note 粘贴到函数外部定义的 paintArray=[]
。
console
为 fillArray()
记录“1”,但是当我 运行 logArray()
紧接着它记录 [].
const paintArray = []
function logArray(){
console.log(paintArray)
}
function fillArray(){
paintArray.push(1)
console.log(paintArray)
}
您可以这样使用Properties Service:
var scriptProp = PropertiesService.getScriptProperties();
function logArray(){
Logger.log(scriptProp.getProperty("paintArray"))
}
function fillArray(){
var obj = scriptProp.getProperty("paintArray")
if(obj){ //check if paintArray Object exists
var arr = JSON.parse(obj); //parse the value to array
arr.push(1); //push value 1
scriptProp.setProperty("paintArray", JSON.stringify(arr)) //set new value of arr to properties
}else{
scriptProp.setProperty("paintArray", "[1]"); //set initial value if paintArray object is undefined
}
}
第一个运行:
第二个运行:
第三个运行:
从属性服务中保存和检索数组
function saveArray(a) {
PropertiesService.getScriptProperties().setProperty("myarray",JSON.stringify(a));
}
function getArray() {
return JSON.parse(PropertiesService.getScriptProperties().getProperty("myarray"));
}
此问题是寻找 paintArray=[]
。
console
为 fillArray()
记录“1”,但是当我 运行 logArray()
紧接着它记录 [].
const paintArray = []
function logArray(){
console.log(paintArray)
}
function fillArray(){
paintArray.push(1)
console.log(paintArray)
}
您可以这样使用Properties Service:
var scriptProp = PropertiesService.getScriptProperties();
function logArray(){
Logger.log(scriptProp.getProperty("paintArray"))
}
function fillArray(){
var obj = scriptProp.getProperty("paintArray")
if(obj){ //check if paintArray Object exists
var arr = JSON.parse(obj); //parse the value to array
arr.push(1); //push value 1
scriptProp.setProperty("paintArray", JSON.stringify(arr)) //set new value of arr to properties
}else{
scriptProp.setProperty("paintArray", "[1]"); //set initial value if paintArray object is undefined
}
}
第一个运行:
第二个运行:
第三个运行:
从属性服务中保存和检索数组
function saveArray(a) {
PropertiesService.getScriptProperties().setProperty("myarray",JSON.stringify(a));
}
function getArray() {
return JSON.parse(PropertiesService.getScriptProperties().getProperty("myarray"));
}