Repeating an action: for and while
A loop repeats an action: going through all of a customer's invoices to add them up, creating one line per month, checking every record of a table…
A for loop can be used to execute code and/or return an array of values. The type of the returned array corresponds to the type of the last statement between do and end.
For Loop
Looping Through a Range of Numbers:
for i from 1 to 10 do
i;
end;Looping Through an Array:
var myArray := [1, 3, 5, 7];
for i in myArray do
i;
end;Looping Through Keys and Values of a JSON Object:
var config := {
sep: ",",
qut: """",
lf: "%0D%0A",
numberFormat: "point",
dateFormat: "locale",
header: true,
sepHeader: false,
encoding: "utf8"
};
for key, value in config do
key + " = " + value;
end;See how to manipulate JSON variables in Ninox: Working with JSON data.
It is also possible to do the same with a record, but you need to use NativeJS from Ninext to transform a record (nid) into JSON:
var rec := (first(select Customer));
"Transforming a record into a JSON object";
var config := #{:any return rec}#;
for fieldName, value in config do
fieldName + " = " + value;
end;This approach can be useful for exporting all fields of a table into formats like CSV. Two precautions:
- Besides the fields designated by their caption, the resulting object contains the technical keys
Id,ID,idand_node, and its values are raw (a date, for example, is a number of milliseconds there). Leave these keys out for an export. - The
#{ … }#block only runs in the browser where Ninext is loaded: in ado as serveror in a table trigger (after create, after update), it has no effect. Ninext's Errors tab reports it.
While Loop
While loops are simple and do not return any value. They are used solely for performing iterative tasks and cannot be used to build arrays.
Example:
var a := 1;
while a < 10 do
a := a + 1;
end;