Hi everybody
this is a trick to create a custom loop in javascript to loop through the arrays,
the full code of our custom loop:
// create a global object jBinfo
var jBinfo = {
/* create a function foreach under the object jBinfo
this function have two parameters table an array and callback it's a function
*/
foreach : function(table, callback) {
// loop the array "table"
for (item in table) {
/* if the callback have one parameter then I call the function "callback(table[item])"
and I pass juste the value "table[item]"; if callback have more parameters
then I pass the index and the value "callback(item, table[item])"*/
if (callback.length == 1) {
callback(table[item]);
} else if (callback.length > 1) {
callback(item, table[item]);
}
}
}
};
// Example 1:
var my_array_1 = new Array('0000', '1111', '2222', '3333');
jBinfo.foreach(my_array_1, function(index, value) {
console.log('index: ' + index + ', value: ' + value);
});
/* the output of example 1:
index: 0, value: 0000
index: 1, value: 1111
index: 2, value: 2222
index: 3, value: 3333
*/
// Example 2: Associative Arrays
var my_array_2 = new Array();
my_array_2['a'] = 'aaaa';
my_array_2['b'] = 'bbbb';
my_array_2['c'] = 'cccc';
my_array_2['d'] = 'dddd';
jBinfo.foreach(my_array_2, function(index, value) {
console.log('index: ' + index + ', value: ' + value);
});
/* the output of example 2:
index: a, value: aaaa
index: b, value: bbbb
index: c, value: cccc
index: d, value: dddd
*/
the callback in my examples is this:
function(index, value) {
console.log('index: ' + index + ', value: ' + value);
}
Thank's