Javascript
Create an regular expression object
Replace string 'aaa' by 'xyz'.
Toggle line numbers
1 var stringx = 'aaa bbb ccc';
2 var regexx = new RegExp('aaa','g');
3 stringx = stringx.replace( regexx , 'xyz' );
Delete property from object
Toggle line numbers
1 delete obj['propertyName'];
Number of milliseconds since epoch
Toggle line numbers
1 var nrmillis = Date.now();
Foreach in array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
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.
Toggle line numbers
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
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.
bind, JSON and arguments sample
Toggle line numbers
1 #!/usr/bin/js
2 // SpiderMonkey JavaScript example code
3 // simulate console.log in SpiderMonkey
4 var console={
5 log: function(msg) {
6 //putstr( msg + "\n");
7 print( msg );
8 }
9 };
10
11 function add(){
12 if(this.hasOwnProperty("op1") ) {
13 console.log("op1 ..." + (this.op1 + this.op2) );
14 }
15
16 if(this.hasOwnProperty("op3") ) {
17 console.log("op3 ..." + (this['op3'] + this['op4']) );
18 }
19
20 if(arguments.length>0) {
21 console.log( arguments[0] );
22 }
23 }
24
25 //---------------------------------------
26 console.log("JSON sample ....");
27 var strx='{"ds":1122 , "hg":"ccvbn" }';
28 var objx = JSON.parse( strx );
29 console.log( objx.ds );
30 console.log( objx.hg );
31 objx.ds = objx.ds*2;
32 console.log( objx.ds );
33 console.log( JSON.stringify( objx ) );
34
35 //---------------------------------------
36 console.log("bind sample");
37 var x={"op1":10, "op2":2};
38 var y={"op3":20, "op4":30};
39 var z={"op1":10,"op2":13};
40 var xxx = add.bind(x); // sets the this context with x object
41 xxx("Arg test") // calls add with an argument
42 var zzz = add.bind(y); // sets this context with y object
43 zzz(); // calls add
44 add.call(z); // sets this context and calls the function add
45
Iterate keys in JSON object
Toggle line numbers
1 for (var key in response.result) {
2 if (response.result.hasOwnProperty(key)) {
3 }
4 }