Javascript Array each(fn)

Description

Javascript Array each(fn)



Array.prototype.each = function(fn) {
  for (var i = 0; i < this.length; i++) fn(this[i]);
}

Javascript Array each(fn)

Array.prototype.each = function(fn) {
    if (!fn) return false;
    for(let i = 0, len = this.length; i < len; i++) {
        if (fn(this[i], i) === false) return false;
    }//from   w w w .j  a  va 2 s .  com
}

Javascript Array each(fn)

Array.prototype.each = function(fn)
{
 for (var i=0; i<this.length; i++)
  fn.apply(this[i], [i]);/*  ww w  .j a v a2 s  .  co  m*/
};

Javascript Array each(fn)

/**/*from w  ww  .  j  a va 2 s  .  c  o m*/
 * Created by wdy on 2017/5/7.
 */


var arr = [1, 2, 3, [4, [5, 6]]];

Array.prototype.each = function (fn) {
    try{
        this.i || (this.i = 0);
        if (this.length>0 && (fn.constructor == Function)){
            while (this.i < this.length){
                var e = this[this.i];
                if (e && e.constructor == Array){
                    e.each(fn)
                }else {
                    fn.call(e,e);
                }
                this.i ++
            }
        }
    }catch(ex){

    }
    return this
}

arr.each(function (item) {
    console.log(item)
})

Javascript Array each(fn)

Array.prototype.each = function (fn) {
 for (var i=0; i<this.length; i++)
  fn(this[i]);/*www .ja  v  a 2s.  co  m*/
 return this;
};

Javascript Array each(fn)

Array.prototype.each = function (fn) {

    for (var i=0; i<this.length; i++)
        fn(this[i])//from   w  ww. j a  v a 2  s . c  om
}

Array.prototype.inject = function (acum, fn){

    for (var i=0; i<this.length; i++)
        acum = fn(acum, this[i])

    return acum
}

Array.prototype.select_if = function (fn){
    var r = []

    for (var i=0; i<this.length; i++)
        if (fn(this[i]))
          r.push(this[i])
    return r

}

function main() {

    var a = [1,2,3,4,5,6]
    var p = []

    alert(a.inject(1, function(acum, el){
        return acum * el
    }))

    alert( a.select_if(function(el){
        return el % 2
    }).toSource() )

    a.each(function(el){
        if (el > 2 && el % 2 == 1)
            p.push(el)
    })

    p.each(function (el){
        alert(el)
    })

}



PreviousNext

Related