Javascript

Create an regular expression object

Replace string 'aaa' by 'xyz'.

   1 var stringx = 'aaa bbb ccc';
   2 var regexx = new RegExp('aaa','g');
   3 stringx = stringx.replace( regexx , 'xyz' );

Delete property from object

   1 delete obj['propertyName'];

Number of milliseconds since epoch

   1 var nrmillis = Date.now();

Foreach in array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

   1 function logArrayElements(element, index, array) {
   2     console.log("a[" + index + "] = " + element);
   3 }
   4 [2, 5, 9].forEach(logArrayElements);
   5 // logs:
   6 // a[0] = 2
   7 // a[1] = 5
   8 // a[2] = 9
   9 

Context with this and bind

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

   1 /*Constructor function*/
   2 function Counter(){     
   3   this.counter=0;
   4 }
   5 
   6 Counter.prototype.run=function(){
   7   console.log('counter:',this.counter);
   8   this.counter++;
   9   //recall run
  10   setTimeout(this.run.bind(this),1000);
  11 };
  12 
  13 var c = new Counter();
  14 setTimeout( c.run.bind(c) ,1000); // apply context of c to this
  15 

arguments

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments An Array-like object corresponding to the arguments passed to a function. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.

Javascript (last edited 2014-07-10 21:17:00 by 46)