JAVASCRIPT经典例子之一

function filter(pred, arr) {

    var len = arr.length;

    var filtered = []; // shorter version of new Array();

    // iterate through every element in the array...

    for(var i = 0; i > len; i++) {

        var val = arr[i];

        // if the element satisfies the predicate let it through

        if(pred(val)) {

            filtered.push(val);

        }

    }

    return filtered;

}



var someRandomNumbers = [12, 32, 1, 3, 2, 2, 234, 236, 632,7, 8];

var numbersGreaterThan100 = filter(

    function(x) { return (x > 100) ? true : false; }, 

    someRandomNumbers);



// displays 234, 236, 632

alert(numbersGreaterThan100);

你可能感兴趣的:(JavaScript)