Sunday, March 27, 2016

Javascript Foreach Replacements

I am not a fan of the foreach implementation in ES5. Here are some ideas I had to work around it. Some of these are ES6.

Operate on items in an array
Does not update the items in the array
1:  var n = ['cat', 'dog', 'rat'];  
2:  var val;  
3:  for (val of n){  
4:    val = val + 's';  
5:    console.log(val);  
6:  }  
7:  console.log(n);  
more verbose way of doing the same
var n = ['cat', 'dog', 'rat'];
var it = n.values();
var entry;
while (!(entry = it.next()).done) {
    entry.value = entry.value + 's';
    console.log(entry.value);
}
console.log(n);

Operate on items in an array
Updates the items in the array
more verbose way of doing the same
var n = ['cat', 'dog', 'rat'];
for (i in n){
    n[i] = n[i] + 's';
    console.log(n[i]);
}
console.log(n);
same as above but unpleasantly verbose
var n = ['cat', 'dog', 'rat'];
for (i = 0; i < n.length ;i++){
    n[i] = n[i] + 's';
    console.log(n[i]);
}
console.log(n);

Performantly operate on items in a sparse array. Updates the defined items in the array additional checks may be required if order is required to be consistent
see link below
var n = ['cat', 'dog', 'rat'];
n[10] = 'goat';
n[17] = 'chupacabra';
for (i in n){
    if(String(parseInt(i, 10)) === i && n.hasOwnProperty(i))
    n[i] = n[i] + 's';
    console.log(n[i]);
    }
}
console.log(n);
Syntax I wanted to avoid
mozilla forEach

Source of inspiration
Arrays

No comments:

Post a Comment