Javascript Number times(f, context)

Description

Javascript Number times(f, context)


Number.prototype.times = function ( f, context ) {
 var n = this.valueOf();
 for (var i = 0; i < n; i++) {
  f.call(context, i);//from  w ww. j  a  va  2 s.c  o  m
 }
};

var n = 3; // 1
n.times( function( n ) {
 console.log("Hello!");
});

Number.prototype.times = function(f, context){
  var n = Number(this);
  for(var i = 0; i < n; i++){
    f.call(context, i);//from   w  w  w  . j  ava 2 s .c  om
  }
};

String.prototype.trim = String.prototype.trim || function(){
  if (!this) return this;
  return this.replace(/^\s+|\s+$/g, "");
}

Function.prototype.getName = function(){
  return this.name || this.toString().match(/function\s*([^(]*)\(/)[1];
};

function test(){
  var n = 3;
  n.times(function(n){ console.log(n + " hello");});
  var t = "    abcde     ";
  console.log(t.trim());
}

Javascript Number times(f, context)

function Range(from, to) {
    this.from = from;//  ww w.  j  a v  a2s  .  co m
    this.to = to;
};

Range.prototype = {
    constructor: Range,
    includes: function(x) {
        return this.from <= x && x <= this.to;
    },
    foreach: function(f) {
        for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
    },
    toString: function() {
        return "(" + this.from + "..." + this.to + ")";
    }
};

var r = new Range(1,3);
r.includes(2);
r.foreach(console.log);
console.log(r);



Number.prototype.times = function(f, context){
    var n = Number(this);
    for(var i = 0; i < n; i++) {
        f.call(context, i);
    }
};

var n = 3;
n.times(function(n) {
    console.log(n + "Hello")
});

Javascript Number times(f,context)


Number.prototype.times = function(f,context){
 console.log(f.toString());/*from  www.  jav a 2 s .  c o m*/
 console.log(this)
 var n = Number(this);
 for(var i = 0;i<n;i++){
  f.call(context,i);
 }
}

var n = 3;
n.times(function(n){//different n
 console.log(n + " times");
});


//wrong: 3 won't be cast to object
//3.times(function(n){console.log(n + " times");});



PreviousNext

Related