Here a simple code i'm trying to run in google sheets script.
The purpose is supplying the foreach callback function additional parameters.
function print(str, num) {
Logger.log(str + ": " + num);
}
function test()
{
var array = [1,2,3];
var str = "Stam";
//This line has an exception
// TypeError: Cannot convert null to an object
array.forEach(print.bind(null, str));
}
test();
this code is based on the solution described here.
I know there are other solutions, though i want to understand why this one does not work.
I wounder maybe it is not supported with google sheets.
How about this answer? Please think of this as just one of several possible answers.
At Javascript, when
nullofbind(null, str)is used,thisis used. At Google Apps Script, whennullis used forbind(null, str), an error occurs like "Cannot convert null to an object". I think that this might be the specification of Google side. I'm not sure whether this is modified in the future update. So as the current workaround, how about usingthisinstead ofnull? Or if you want to usebind(null, str)likenullunder the strict mode, how about using{}instead ofnulllikebind({}, str)?By the way, I think that
test();at the last line of your script can be removed. Because in your case, whentest()is run at the script editor,test()is run 2 times bytest();at the last line.test();at the last line is run as the global.From above situation, when your script is modified, how about the following modification?
Modified script:
or you can also modify
test()of your script as follows. The followingtest()retrieves the same result with above one.Result:
When you run
test()at the script editor, you can see the following result at the log.Reference:
If I misunderstood your question and this was not the direction you want, I apologize.