I have an array prototype method for doing things like this, similar to php's array_walk, just pass it the name of a function you have defined to do the job on each member of the array, each member of the array will have the function performed on it. Note the function defined, in this case alterNum() must accept an argument which will be the member of the array, and return a value.
Code:
<script type="text/javascript">
Array.prototype.changeEach = function (func) {
var z = 0;
while (z < this.length) {
if (this[z] instanceof Array) { //go multiple levels deep if member is another array
this[z].changeEach(func);
} else {
this[z] = func(this[z]); //run the function on the individual member
}
z++;
}
};
var arr = [0, 5, 9, 2, 1, 6, 8, 7];
function alterNum(num) {
return (typeof num == 'number' && num > 5) ? num - 1 : num;
}
arr.changeEach(alterNum);
alert(arr); //0,5,8,2,1,5,7,6
</script>
Actually, I just got around to re-working that changeEach method (I've been meaning to, but forgot til now..) as it only works on numerical arrays. The newly modified version works on associative arrays also, might as well share it:
HTML Code:
<html><body><script type="text/javascript">
Array.prototype.changeEach = function (func) {
if (typeof func == 'function') {
var prop;
for (prop in this) {
if (this[prop] instanceof Array) { //if member is another array, go multiple levels deep
this[prop].changeEach(func);
} else { //run func on individual member
this[prop] = func(this[prop]);
}
}
}
};
var arr = [0, 5, 9, 2, 1, 6, 8, 7];
var arr2 = [];
arr2["bob"] = 3;
arr2["fred"] = 7;
arr2["john"] = 5;
arr2["sue"] = 22;
arr2["multi"] = [4,8,12];
function alterNum(num) {
return (typeof num == 'number' && num > 5) ? num - 1 : num;
}
arr.changeEach(alterNum);
alert(arr);
arr2.changeEach(alterNum);
alert(arr2.fred);
alert(arr2.multi[2]);
</script></body></html>
Bookmarks