function forEach(array, action) {
for ( var i = 0; i < array.length; i++) {
action(array[i]);
}
}
forEach([ "Pear" , "Apple" ], function (name) {
console.log(name);
});
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
//兼容版 function(callback, opt_initialValue){
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError(
'Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index, value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
}
else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
function countZeros(array) {
function counter(total, elem) {
return total + (elem == 0 ? 1 : 0);
}
return reduce(counter, 0, array);
}
alert( "countZeros by reduce: " + countZeros([1, 3, 0, 4, 7, 0]));
function sum(array) {
function add(a, b) {
return a + b;
}
return reduce(add, 0, array);
}
alert( "sum by reduce: " + sum([1, 2, 3, 5]));
function map(func, array) {
var result = [];
forEach(array, function (elem) {
result.push(func(elem));
});
return result;
}
var array = [1, 2, 3, 4, 5];
var mappedArray = map( function (elem) {
return elem * 2;
}, array);
console.log(mappedArray);
var array2 = [1.3, 4.5, 6.7, 8, 9.2];
var mappedArray2 = map(Math.floor, array2);
console.log(mappedArray2);
function filter(func, array) {
var result = [];
forEach(array, function (elem) {
if (func(elem))
result.push(elem);
});
return result;
}
function isEven(elem) {
return elem % 2 == 0;
}
var array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var filterArray = filter(isEven, array3);
console.log(filterArray);
|