Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial68 Looping through Objects
Looping through the properties of an object is similar to that as with array, except with looping through the keys of the object instead of indexes:
function HandleMIDI(event) {
var keys = Object.keys(event);
var length = keys.length;
for ( var thisKey = 0; thisKey < length; thisKey++ ) {
var key = keys[thisKey];
var value = event[key];
Trace( key + ":" + value );
}
}In the above example:
Line 1: Scripter executes the
HandleMIDI()function whenever a new event is encountered. The event is anObjectwith keys used to get their values.Line 2: The
Object.keys()function is called to get an array of all the object’s keys.Line 3: The length of the keys array is captured.
Line 4: The
forstatement is declared.var thisKey = 0declares the loop’s variable. The value will be used as the index to get strings from thekeysarray.thisKey < lengthis the condition to be tested. When the index is less than the length, the code block is executed. When the condition is false—thisKeyequals length—–the loop is immediately stopped.thisKey++will add 1 the value of thisKey after the code block has been executed.