问题
I was working on this project and I wanted to make a function that displays an element of a specific column.
Now with javascript I can call any element of an array with
Array[i]
But for some reason this doesn't seem to work in Google Spreadsheets.
var MyFunction(A) {
return A[1];
}
This function yields me nothing.
EDIt: I solved it. I used this loop with a sort of double indexing:
for (var i=0; i < 37; i++) {
if (A[0][i] < max && A[0][i] != 0) {
var max = A[0][i];
};
};
A[0][0] is the first element if I select a row vector in spreadsheet. For example, If I select A2:A5 as A, A[0][0] will give me the value of cell A2! Thanks for the help!
回答1:
Try this instead:
var MyFunction(A) {
return A[0];
}
The assumption I making here is you are trying to return the first element in the index. In javascript Array index starts at 0 and not 1.
回答2:
It doesn't work that way. You have to first allow access to the spreadsheet then tell Apps Script which Spreadsheet you're working on through openById. After that you can now access the data. Here's a simple code snippet for you. I'm using the standalone mode. There maybe other ways of doing this.
We're going to access this sheet. I've included the index numbers so you can easily understand:
Then we create a function named fetchValue
which accepts 2 parameters- the row and the column.
We execute main
function which makes calls to fetchValue
.
function main(){
Logger.log("the value returned was "+ fetchValue(1,1) ); //returns las vegas
}
function fetchValue(row,col) {
var sheet = SpreadsheetApp.openById("SPREADSHEET_ID_HERE");
var data = sheet.getDataRange().getValues();
return data[row][col];
}
We then view the Logs if it returned the value of index 1,1 which is las vegas
.
Make sure the row and column you pass to fetchValue
is within range else it will return errors.
来源:https://stackoverflow.com/questions/42476150/how-to-index-arrays-in-google-apps-script