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 null
of bind(null, str)
is used, this
is used. At Google Apps Script, when null
is used for bind(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 using this
instead of null
? Or if you want to use bind(null, str)
like null
under the strict mode, how about using {}
instead of null
like bind({}, str)
?
By the way, I think that test();
at the last line of your script can be removed. Because in your case, when test()
is run at the script editor, test()
is run 2 times by test();
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?
function print(str, num) {
Logger.log(str + ": " + num);
}
function test() {
var array = [1,2,3];
var str = "Stam";
array.forEach(print.bind(this, str));
}
or you can also modify test()
of your script as follows. The following test()
retrieves the same result with above one.
function test() {
var array = [1,2,3];
var str = "Stam";
array.forEach(function(e) {print(str, e)});
}
When you run test()
at the script editor, you can see the following result at the log.
Stam: 1
Stam: 2
Stam: 3
If I misunderstood your question and this was not the direction you want, I apologize.