Javascript Language Tips & Tricks

Google wikiden alınmıştır. İngilizcedir

Javascript Language Tips & Tricks

Named optional function arguments

function foo({ name:name, project:project}) {

    Print( project );
    Print( name );
}

foo({ name:'soubok', project:'jslibs' })
foo({ project:'jslibs', name:'soubok'})



Floating to integer

(123.345456).toFixed(); // is: 123
typeof (1.5).toFixed(); // is: string



String converter JavaScript 1.8

function CreateTranslator(translationTable) function(s) s.replace(new RegExp([k for (k in translationTable)].join('|'), 'g'), function(str) translationTable[str]);

//exemple of use:

var translationTable = { a:1, bb:2, b:3, c:4 };
var MyTranslater = CreateTranslator( translationTable );
MyTranslater('aabbbc'); // returns: 11234



Display the current call stack JavaScript 1.6

function Stack() { try { throw Error() } catch(ex) { return ex.stack } }

print( Stack() );

//prints:

Error()@:0
Stack()@test.js:1
@test.js:3



Get the number of properties of an object JavaScript ???

({ foo:55, bar:99 }).__count__ // is: 2



Check if an object is not empty JavaScript 1.5

function isNotEmpty(obj) {
        for ( var tmp in obj )
                return true
}

//JavaScript 1.8

function isNotEmpty(obj) obj.__count__;



Change the primitive value an object with valueOf

function foo() {

   this.valueOf = function() {

     return 'this is my value';
   }
}

var bar = new foo();

Print( bar ); // prints: this is my value



Transform the arguments object into an array JavaScript ???

function foo() {

  Array.slice(arguments); // is ['aa',11]
}

foo('aa',11);



Convert a string into a charcode list

//Method 1: JavaScript 1.6

Array.map('foo', function(x) { return String.charCodeAt(x) }) // is [112,111,111]

//Method 2: JavaScript 1.7

[ String.charCodeAt(x) for each ( x in 'foo' ) ] // is [112,111,111]



Array iteration pitfall

var foo = [3,4,5];

for ( var i in foo ) {

  if ( i == 1 ) {
    foo.splice(1,1)
    foo.push(999)
  }

  Print( foo.toSource() )
}

//output:

[3, 4, 5]
[3, 5, 999]
[3, 5, 999]

//To workaround this, we just have to iterate over a copy of the array:

...
for ( var i in foo.slice() ) {
...



exceptions for non-fatal errors
JavaScript 1.6

function ERR() { throw ERR }
function CHK( v ) { return v || ERR() }

try {
       
  var data1 = 'a/b/c';
  var arr1 = CHK(data1).split('/');

  var data2 = '';
  var arr2 = CHK(data2).split('/'); // the exception is throw here

} catch(ex if ex == ERR) {

  Print('non fatal error while decoding the data')
}

//prints:

//a b c



A Switch function JavaScript 1.8

function Switch(i) arguments[++i];

//usage:

Print( Switch(2,'aa','bb','cc','dd') ); // prints: cc
Print( Switch(100,'aa','bb','cc','dd') ); // prints: undefined



A Match function JavaScript 1.8

function Match(v) Array.indexOf(arguments,v,1)-1;

//usage:

Print( Match('aa', '0', 'b', 123, 'aa', 8.999 ) ); // prints: 3
Print( Match('Z', 'b', 123, 'aa', 8.999 ) ); // prints: -2 (< 0 is not found)



new object override JavaScript 1.5

function foo() {

  return new Array(5,6,7);
}

var bar = new foo();
bar.length // is 3



Destructuring assignments JavaScript 1.7

var {a:x} = {a:7};
Print(x); // prints: 7



Generator Expressions JavaScript 1.7

[ y for ( y in [5,6,7,8,9] ) ] // is [0,1,2,3,4]

//and

[ y for each ( y in [5,6,7,8,9] ) ] // is [5,6,7,8,9]

//Because in for extracts index names, and for each extracts the values.



Advanced use of iterators JavaScript 1.8

Number.prototype.__iterator__ = function() {

 for ( let i = 0; i < this; i++ )
  yield i;
};

for ( let i in 5 )
 print(i);

//prints:

1
2
3
4
5

//This make Number object to act as a generator.



Expression Closures JavaScript 1.8

function(x) x * x;

//Note that braces {...} and return are implicit



Function declaration and expression

//Function declaration:

bar(); // prints: bar
function bar() {

   Print('bar');
}

function foo() {

   Print('foo');
}
foo(); // prints: foo

//Function expression:

(function foo() {
  Print( foo.name );
})(); // prints: foo
foo(); // rise a ReferenceError

!function foo() {
}
foo(); // rise a ReferenceError

var bar = function foo() {
}
foo(); // rise a ReferenceError



Factory method pattern

Complex = new function() {

        function Complex(a, b) {
                // ...
        }

        this.fromCartesian = function(real, mag) {

                return new Complex(real, imag);
        }

        this.fromPolar = function(rho, theta) {

                return new Complex(rho * Math.cos(theta), rho * Math.sin(theta));
        }
}


var c = Complex.fromPolar(1, Math.pi); // Same as fromCartesian(-1, 0);



Closures by example JavaScript 1.5

function CreateAdder( add ) {

  return function( value ) {
 
    return value + add;
  }
}

//usage:

var myAdder5 = CreateAdder( 5 );
var myAdder6 = CreateAdder( 6 );

Print( myAdder5( 2 ) ); // prints 7
Print( myAdder6( 4 ) ); // prints 10



SyntaxError JavaScript 1.5

//raised when a syntax error occurs while parsing code in eval()

try {

  eval('1 + * 5'); // will rise a SyntaxError exception
       
} catch( ex ) {

        Print( ex.constructor == SyntaxError ); // Prints true
}



ReferenceError

//raised when de-referencing an invalid reference.

try {

  fooBar(); // will rise a ReferenceError exception
       
} catch( ex ) {

        Print( ex.constructor == ReferenceError ); // Prints true
}



JavaScript Minifier / comment remover

var script = new Script('var a; /* this is a variable */ var b; // another variable');
Print( script.toString() );

//prints:

var a;
var b;



Auto indent JavaScript code / unobfuscator


//Spidermonkey JavaScript engine only

function foo() { function bar(){};var i=0;for(;i<10;++i) bar(i) }
Print(foo.toSource(2));

//prints:

function foo() {

      function bar() {
      }

      var i = 0;
      for (; i < 10; ++i) {
          bar(i);
      }
  }



Objects, constructor and instanceof JavaScript 1.5

function Foo() {
  // Foo class
}

var a = new Foo();


Bar.prototype = new Foo();
function Bar() {
  // Bar class
}

var b = new Bar();


Print( a.constructor == Foo ); // true
Print( a instanceof Foo ); // true

Print( b.constructor == Foo ); // true
Print( b instanceof Foo ); // true

Print( b.constructor == Bar ); // false !
Print( b instanceof Bar ); // true



Objects private and public members

function MyConstructor( pub, priv ) {

  var privateVariable = priv;
  this.publicVariable = pub;

  this.SetThePrivateVariable = function( value ) {

    privateVariable = value;
  }

  this.GetThePrivateVariable = function() {

    return privateVariable;
  }

  this.PrintAllVariables = function() {

    Print( privateVariable + ',' + this.publicVariable );
  }
}

var myObject = new MyConstructor( 123, 456 );

Print( myObject.privateVariable ); // prints: undefined
Print( myObject.publicVariable ); // prints: 123
myObject.PrintAllVariables(); // prints 456,123
myObject.SetThePrivateVariable( 789 );
myObject.PrintAllVariables(); // prints 789,123



Stack data structure JavaScript 1.5

//Array object has all needed methods to be used as a stack.

  var stack = [];
  stack.push( 111 );
  stack.push( 2.22 );
  stack.push( 'ccc' );

  Print( stack ); // prints: 111,2.22,ccc

  Print( stack.pop() ); // prints: ccc
  Print( stack.pop() ); // prints: 2.22



Singleton pattern JavaScript 1.5

//The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

function MySingletonClass() {

  if ( arguments.callee._singletonInstance )
    return arguments.callee._singletonInstance;
  arguments.callee._singletonInstance = this;

  this.Foo = function() {
    // ...
  }
}

var a = new MySingletonClass()
var b = MySingletonClass()
Print( a === b ); // prints: true



Use Functions as an Object JavaScript 1.5

function Counter() {
   
   if ( !arguments.callee.count ) {
   
        arguments.callee.count = 0;
    }
    return arguments.callee.count++;
}
Print( Counter() ); // prints: 0
Print( Counter() ); // prints: 1
Print( Counter() ); // prints: 2



E4X add nodes JavaScript 1.6

var x = <store/>;
x.* += <item price="10" />;
x.* += <item price="15" />;
Print( x.toXMLString() );

//prints:

<store>
  <item price="10"/>
  <item price="15"/>
</store>



E4X dynamic document creation JavaScript 1.6

var html = <html/>;
html.head.title = "My Page Title";
html.body.@bgcolor = "#e4e4e4";
html.body.form.@name = "myform";
html.body.form.@action = "someurl.jss";
html.body.form.@method = "post";
html.body.form.@onclick = "return somejs();";
html.body.form.input[0] = "";
html.body.form.input[0].@name = "test";
Print(html.toXMLString());

//prints:

<html>
  <head>
    <title>My Page Title</title>
  </head>
  <body bgcolor="#e4e4e4">
    <form name="myform" action="someurl.jss" method="post" onclick="return somejs();">
      <input name="test"></input>
    </form>
  </body>
</html>



E4X dynamic tag name JavaScript 1.6

var nodeName = 'FOO';
if ( isXMLName(nodeName) ) { // assert that nodeName can be used as a node name
  var x = <{nodeName}>test</{nodeName}>
  Print( x.toXMLString() ); // prints: <FOO>test</FOO>
}



E4X dynamic content JavaScript 1.6

var content = 'FOO';
var x = <item>{content}</item>
Print( x.toXMLString() ); // prints: <item>FOO</item>



E4X iteration JavaScript 1.6

var sales =
<sales vendor="John">
  <item type="peas" price="4" quantity="5"/>
  <item type="carrot" price="3" quantity="10"/>
  <item type="chips" price="5" quantity="3"/>
</sales>;
 
for each( var price in sales..@price ) {
  Print( price + '\n' );
}

//prints:

4
3
5



Listen a property for changes

function onFooChange( id, oldval, newval ) {

  Print( id + " property changed from " + oldval + " to " + newval );
  return newval;
}

var o = { foo:5 };
o.watch( 'foo', onFooChange );

o.foo = 6;

delete o.foo;

o.foo = 7;

o.unwatch('foo');
o.foo = 8;

//prints:

foo property changed from 5 to 6
foo property changed from undefined to 7



Logical operators tricks

var a = 5;
a == 5 && Print( 'a is 5 \n' );
a == 7 || Print( 'a is not 7 \n' );

//prints:

a is 5
a is not 7



Functions argument default value

function foo( a, b ) {

  a = a || '123';
  b = b || 55;
  Print( a + ',' + b );
}

foo(); // prints: 123,55
foo('bar'); // prints: bar,55
foo('x', 'y'); // prints x,y

//but:

foo(0,''); // prints: 123,55

//because 0 and '' are evaluated as false !



Remove an item by value in an Array object

var arr = ['a', 'b', 'c', 'd'];
var pos = arr.indexOf( 'c' );
pos > -1 && arr.splice( pos, 1 );
Print( arr ); // prints: a,b,d



Multiple-value returns JavaScript 1.7

function f() {

  return [1, 2];
}

var [a, b] = f();

Print( a + ' ' + b ); // prints: 1 2




Operator [ ] and strings ( like charAt() ) JavaScript 1.6

var str = 'foobar';
Print( str[4] );

//prints:

a



indexOf() and lastIndexOf() Works on Array JavaScript 1.6

var obj = {};
var arr = [ 'foo', 567, obj, 12.34 ];
Print( arr.indexOf(obj) ); // prints: 2



Using Array functions on a non-Array object JavaScript 1.7

var obj = {};
Array.push(obj, 'foo');
Array.push(obj, 123);
Array.push(obj, 5.55);
Print( obj.toSource() ); // prints: ({0:"foo", length:3, 1:123, 2:5.55})



Simulate threads using yield operator JavaScript 1.7

var scheduler = new function() {

  var _workers = [];

  this.Add = function( worker ) {

    _workers.push( new worker() );
  }

  this.Run = function() {

    while ( _workers.length )
      for each ( var worker in _workers )
        try {
          worker.next();
        } catch (err if err instanceof StopIteration) {
          _workers.splice( _workers.indexOf(worker), 1 );
        }
  }
}

function worker1() {

  for ( var i = 0; i < 5; i++ ) {

    Print( 'worker1: '+i, '\n' );
    yield;
  }
}

scheduler.Add(worker1);

function worker2() {

  for ( var i = 0; i < 10; i++ ) {

    Print( 'worker2: '+i, '\n' );
    yield;
  }
}

scheduler.Add(worker2);

scheduler.Run();

//prints:

worker1: 0
worker2: 0
worker1: 1
worker2: 1
worker1: 2
worker2: 2
worker1: 3
worker2: 3
worker1: 4
worker2: 4
worker2: 5
worker2: 6
worker2: 7
worker2: 8
worker2: 9



Change current object (this) of a function call

function test(arg) {

  Print( this[0]+' '+this[1]+' '+arg );
}

var arr = ['foo', 'bar'];
test.call(arr, 'toto'); // prints: foo bar toto



Filter / intercept a function call

function bar(a, b, c, d, e, f) {

  Print(a, b, c, d, e, f)
}

function foo() {

  bar.apply(this, arguments);
}

foo(1, 2, 3, 4, 5, 6); // prints: 123456



E4X Query ( like XPath )

JavaScript 1.6

var xml = <mytree>
 <data id="1" text="foo"/>
 <data id="2" text="bar"/>
</mytree>

Print( xml.data.(@id==1).@text );
var myid = 2;
Print( xml.data.(@id==myid).@text );

//prints:

foo
bar



swap two variables JavaScript 1.7

var a = 1;
var b = 2;
[a,b] = [b,a];



Destructuring assignment with function arguments JavaScript 1.7

function foo( [a,b] ) {

        Print(a);
        Print(b);
}

foo( [12,34] );

//Prints:

12
34



JavaScript scope is not C/C++ scope

if ( false ) { // never reach the next line

        var foo = 123;
}

Print(foo); // prints: undefined ( but is defined )
Print(bar); // failed: ReferenceError: bar is not defined



JavaScript scope and LET instruction JavaScript 1.7

var x = 5;
var y = 0;
let (x = x+10, y = 12) {
  Print(x+y);
}
Print(x+y);

//prints:

27
5

//or,

for ( let i=0 ; i < 10 ; i++ ) {
  Print(i + ' ');
}
Print(i);

//prints:

0 1 2 3 4 5 6 7 8 9 test.js:4: ReferenceError: i is not defined



Defer function calls

var opList = [];
function deferCall( text, value ) {
        opList.push(arguments)
}
function doCall(func) {
        while (opList.length)
                func.apply(this,opList.shift());
}

deferCall( 'one', 1 );
deferCall( 'titi', 'toto' );
deferCall( 5, 'foo' );

function callLater(a,b) {
 
Print(a+', '+b);
}

doCall( callLater )

//Prints:

one, 1
titi, toto
5, foo



Insert an array in another array

var a = [1,2,3,4,5,6]
var b = ['a','b','c']
var insertIndex = 5;

Array.concat( a.splice( 0, insertIndex ), b, a )

//result:

1,2,3,4,5,a,b,c,6



Multiple string concatenation

var html = ['aaa', 'bbb', 'ccc', ...].join('');

//Is faster than:

var html = 'aaa' + 'bbb' + 'ccc' + ...;

//This is true with a big number of elements ( > 5000 )



HTTP headers parser

var rexp_keyval = /(.*?): ?(.*?)\r?\n/g;
function headersToObject( allHeaders ) {

        var res, hdrObj = {};
        for ( rexp_keyval.lastIndex = 0; res = rexp_keyval.exec(allHeaders); hdrObj[res[1]] = res[2])
        return hdrObj;
}



Using 'with' scope

with({ a:5 }) function toto() { return a }
toto() // returns 5

(object).toString()

var a = { toString:function() { return '123'; }  }
Print(a); // prints '123', and not [Object object]



RegExpr.$1

var re = /a(.*)/
'abcd'.match(re)
Print( RegExp.$1 ) // prints 'bcd'



Binary with XmlHTTPRequest

//browser related example

var req = new XMLHttpRequest();
req.open('GET', "http://code.google.com/images/code_sm.png",false);
req.overrideMimeType('text/plain; charset=x-user-defined');
//req.overrideMimeType('application/octet-stream');
req.send(null);
var val = req.responseText;
Print( escape(val.substr(0,10)) );



Iterate on values JavaScript 1.6

for each ( var i in [3,23,4] )
        Print(i)

//Prints:

3
23
4



Exceptions Handling / conditional catch (try catch if)

function Toto(){}
function Titi(){}

try {

        throw new Titi()

} catch ( err if err instanceof Toto ) {
        Print('toto')
} catch ( err if err instanceof Titi ) {
        Print('titi')
} catch(ex) {
        throw(ex);
}



Special chars

$=4
_=5
Print( _+$)

//prints:

9



object's eval method

var foo = { bar:123 };
foo.eval('bar') // returns 123

eval this

function test() {

        Print(eval('this'));
}
test.call(123)

//prints:

123



No Such Method ( noSuchMethod )

var o = {}
o.__noSuchMethod__ = function(arg){ Print('unable to call "'+arg+'" function') }
o.foo(234)

//prints:

//unable to call "foo" function



RegExp replace

function Replacer( conversionObject ) {

        var regexpStr = '';
        for ( var k in conversionObject )
                regexpStr += (regexpStr.length ? '|' : '') + k;
        var regexpr = new RegExp(regexpStr,'ig'); // g: global, m:multi-line i: ignore case
        return function(s) { return s.replace(regexpr, function(str, p1, p2, offset, s) { var a = conversionObject[str]; return a == undefined ? str : a }) }
}

var myReplacer = Replacer( { '<BR>':'\n', '&amp;':'&', '&lt;':'<', '&gt;':'>', '&quot;':'"' } );

Print( myReplacer('aa<BR>a &amp;&amp;&amp;&lt;') );

//prints:

aa
a &&&<



Values comparaison

[4] === 4 // is: false
[4] == 4 // is: true

'0' == 0 // is: true
'0' === 0 // is: false



undefined, null, 0, false, '', ...

var a = { b:undefined, c:null, d:0, f:'' }

a['b'] // is: undefined
a['e'] // is: undefined

'b' in a // is: true
'e' in a // is: false

Boolean(a.b) // is: false
Boolean(a.c) // is: false
Boolean(a.d) // is: false
Boolean(a.e) // is: false !
Boolean(a.f) // is: false

typeof( asvqwfevqwefq ) == 'undefined' // =true

Print( '' == false ); // prints: true
Print( 0 == false ); // prints: true
Print( [] == false ); // prints: true

Print( [] == '' ); // prints: true
Print( '' == 0 ); // prints: true
Print( [] == 0 ); // prints: true



constructor property ( InstanceOf + Type )

var a = {};
a.constructor === Object // is: true



AJAX evaluation

var a = {

        b:function() { Print(123) }
}

var body = 'b();';

with(a) { eval(body) }; // Prints 123



Coma operator

var a = 0;
var b = ( a++, 99 );

a // is: 1
b // is: 99

var i = 0;
while( Print('x '), i++<10 )
        Print(i + ' ')

//prints: x 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 10 x



closures pitfall

var a = [];

for ( var i=0; i<10; i++ ) {

 a[i] = function() { Print(i); }
}

a[0](); // is: 10
a[1](); // is: 10
a[2](); // is: 10
a[3](); // is: 10

//simpler case:

var i = 5;
function foo() { Print(i) }
foo(); // prints 5
i = 6;
foo(); // prints 6

//Closure definition

//A closure occurs when one function appears entirely within the body of another, and the inner function refers to local variables of the outer function.

//In the first example, you can avoid the behavior using the let instruction:

var a = [];

for ( var i=0; i<10; i++ ) {
 let j = i;
 a[i] = function() { Print(j); }
}

//In this case, each instances of the (anonymous) inner function refer to different instances of variable j.



sharp variable


var a = { titi:#1={}, toto:#1# };
a.titi === a.toto; // is: true

var a = { b:#1={ c:#1# } }
// a.b.c.c.c.c.c.c...



common object between 2 objects

function a() {}

a.prototype = { b:{} }

c = new a;
d = new a;

c.b.e = 2;

c.b === d.b // is: true !
d.b.e // is: 2



constructor

function a( b ) {

        Print(b);
}

c.prototype = new a;

function c( arg ) {

        this.constructor.apply( this, arg );
};

o = new c( [1,2,3] );

//prints:

undefined
1



JavaScript string can contain null chars

var test = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00';
test.length // is: 10

'new' operator precedence

function test() {

        this.toto = 1234;
}

(new test()).toto // ok ( logical way )

new test().toto // ok

new test.toto // bad !

(new test).toto // ok



constructor usage

function toto( val ) { // parent class

        this.print = function() {

                Print( val );
        }
}

titi.prototype = new toto;

function titi( val ) { // child class
 
        this.constructor(val);
}

(new titi(7)).print(); // prints 7



To object

var obj = Object(123);
obj.foo = 678;
Print( typeof( obj ) + ', ' + obj + ', ' + obj.foo ); // prints: object, 123, 678



Serialize or uneval a variable or an object ( can be nested )

var o = { a:123, b:'test', c:function() { return 987; } }

Print( o.toSource() ); // prints: ({a:123, b:"test", c:(function () {return 987;})})

Print( uneval(obj) ); // prints: ({a:123, b:"test", c:(function () {return 987;})})



JavaScript labels

xxx: {
        Print( 111 )
        break xxx;
        Print( 222 )
}

//prints:

111

for in loop

for ( var i in function(){ return [1, 2, 3] }() )
  Print( i );

//prints:

0
1
2



proto ( prototype property )

var a = {}
var b = {}
a.__proto__ == b.__proto__ // is: true



Numbers and floating point error

Print( 1000000000000000128 ); // prints 1000000000000000100



Number base conversion ( hexadecimal )

(255).toString(16); // is: ff

parseInt( 'ff', 16 ) // is: 255

parseInt('0xff'); // is 255



try / catch / finally

try {

} catch(ex) {

        Print('catch')
} finally {

        Print('finally')
}

//prints:

finally



Object argument

var proto = {

        x: function() { return 'x' }
}

var o1 = new Object( proto );
var o2 = new Object( proto );

o1 == o2 // is: true



object and its prototype

function obj() {}

obj.prototype = { x:1 };
var b = new obj;

obj.prototype = { x:2 };
var c = new obj;

c.x == b.x // is: false



Runtime prototype object

var proto1 = {
        a:function(){ return 1 }
}

var proto2 = {
        a:function(){ return 2 }
}

function createObject( proto ) {

        var cl = function() {}
        cl.prototype = proto;
        return new cl;
}

var v1 = createObject( proto1 ).a
var v2 = createObject( proto2 ).a

Print( v1() );
Print( v2() );

Print( createObject( proto1 ).a === createObject( proto1 ).a );

//prints:

1
2
true



for in loop and undefined value

var o = { x:undefined }
for ( var i in o )
        Print(i)

//prints:

x



Call function in parent class

toto.prototype = new function() {

        this.a = function() {

                Print(456)
        }
};


function toto() {

        this.a=function(){

                Print(123)
                toto.prototype.a.call(this); // or: this.__proto__.a();
        }
}

var o = new toto;
o.a();

//prints:

123
456



getter and setter function

abcd getter = function() {

        Print(345);
}

abcd;
abcd;
abcd;

//prints:

345
345
345



defineGetter ( define getter )


o = {}
o.__defineGetter__('x', function(){ Print('xxx')} )
o.x

//prints:

xxx



check if an object or its prototype has a propery (hasOwnProperty)

var o = { a:1 }
o.__proto__ = { b:2 }

o.hasOwnProperty('a'); // is: true
o.hasOwnProperty('b'); // is: false



check if a property is enumerable (propertyIsEnumerable)

var o = { a:1 }

o.propertyIsEnumerable( 'a' ); // is: true

[].propertyIsEnumerable( 'splice' ); // is: false



find the getter/setter function of an object ( lookup getter )

function test() {

        this.x getter = function(){ Print( 'getter' ) }
        this.x setter = function(){ Print( 'setter' ) }
}

var t = new test
Print( t.__lookupGetter__( 'x' ) );

//prints:

function () {
    Print("getter");
}



suppress array element while iterating it


//the following example will failed :

var a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
for ( var i in a ) {

        if ( a[i] == 1 || a[i] == 2 )
        a.splice( i, 1 );
}
Print( a ); // prints: 0,2,3,4,5,6,7,8,9
Print( a.length ); // prints: 9

//We can use : a[i] == undefined; Or start from the end :

var a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];

for ( var i = a.length - 1; i >= 0; i-- ) {

        if ( a[i] == 0 || a[i] == 8 )
        a.splice( i, 1 );
}
Print( a ); // prints: 1,2,3,4,5,6,7,9
Print( a.length ); // prints: 8



JavaScript arrays

var a = [ 1,2,3 ];
a.x = 'xxx';

for ( var i = 0; i < a.length; i++ )
        Print('a: '+a[i]);

for ( var i in a )
        Print('b: '+a[i]);

//prints:

a: 1
a: 2
a: 3
b: 1
b: 2
b: 3
b: xxx



delete array element

//The following do not work:

var ti = [5,6,7,8];
ti.length // is: 4
delete ti[3]
ti.length // is: 4

//Use 'splice' instead:

ti.splice(3, 1);



Logical operators tricks  // Yerel operatörün hünerleri

var a = 5;
a == 5 && Print( 'a is 5 \n' );
a == 7 || Print( 'a is not 7 \n' );

//prints:

a is 5
a is not 7



Functions argument default value // Fonksiyon argümanı başlangıç değeri ( Fonksiyona yollanan veriler)

function foo( a, b ) {

  a = a || '123';
  b = b || 55;
  Print( a + ' ' + b );
}

foo(); // prints: 123,55
foo('bar'); // prints: bar,55
foo('x', 'y'); // prints x,y

/.but:

foo(0,''); // prints: 123,55

//because 0 and '' are evaluated as false !



Remove an item by value in an Array object // Dizi objesinden bir elemanı değerine göre silmek

var arr = ['a', 'b', 'c', 'd'];
var pos = arr.indexOf( 'c' );
pos > -1 && arr.splice( pos, 1 );
Print(arr);

//prints:

a,b,d



Multiple-value returns // Çoklu değer geri döndürmek (fonksiyonlardan)

function f() {
return [1, 2];
}

var [a, b] = f();
Print( a + ' ' + b )

//prints:

1 2
function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}

var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);

function xyz() {
...
var x = 1;
var y = 'A';
return {x : x, y : y};
}

var a = xyz();
document.write('x=' + a.x + ' and y = ' + a.y);


Operator [ ] and strings ( like charAt() ) // Köşeli parantez oparatörü ve karakterler ( charAt() fonksiyonu gibi kullanmak kö?eli parantezi)

Javascript 1.6

var str = 'foobar';
Print( str[4] );

//prints:

a



indexOf() and lastIndexOf() Works on Array Javascript 1.6 // IndexOf() ve lastIndexOf() fonksiyonlar?n?n bir dizide çalıştırılması

var obj = {};
var arr = ['foo',567, obj];
arr.indexOf(obj);

//returns:

2



Using Array functions on a non-Array object Javascript 1.7 // Dizi olmayan bir objede Dizi fonksiyonun kullan?lmas?

var obj = {};
Array.push(obj, 'foo');
Array.push(obj, 123);
Array.push(obj, 5.55);
arr.toSource();

//result:

({0:"foo", length:3, 1:123, 2:5.55})



Simulate threads using yield operator
Javascript 1.7<// yield işlemcisini kullanarak fonksiyona benzeyen parçaları üretmek

var scheduler = new function() {

  var _workers = [];

  this.Add = function( worker ) {

    _workers.push( new worker() );
  }

  this.Run = function() {

    while ( _workers.length )
      for each ( var worker in _workers )
        try {
          worker.next();
        } catch (err if err instanceof StopIteration) {
          _workers.splice( _workers.indexOf(worker), 1 );
        }
  }
}

function worker1() {

  for ( var i = 0; i < 5; i++ ) {

    Print( 'worker1: '+i, '\n' );
    yield;
  }
}

scheduler.Add(worker1);

function worker2() {

  for ( var i = 0; i < 10; i++ ) {

    Print( 'worker2: '+i, '\n' );
    yield;
  }
}

scheduler.Add(worker2);

scheduler.Run();

//prints:

worker1: 0
worker2: 0
worker1: 1
worker2: 1
worker1: 2
worker2: 2
worker1: 3
worker2: 3
worker1: 4
worker2: 4
worker2: 5
worker2: 6
worker2: 7
worker2: 8
worker2: 9



Change current object (this) of a function call // Kullanılan objeyi bir fonksiyon çağrısı ile değiştirmek

function test(arg) {

  Print( this[0]+' '+this[1]+' '+arg );
}

var arr = ['foo', 'bar'];
test.call(arr, 'toto');

//prints:

foo bar toto



Filter / intercept a function call // Bir fonksiyon çağrısını Filitreleme / Durdurma

function bar(a,b,c,d,e,f) {

  Print(a,b,c,d,e,f)
}

function foo() {

  bar.apply(this,arguments);
}

foo(1,2,3,4,5,6)

prints:

123456

E4X node creation // E4X gözü (parçac???) olu?turma

Javascript 1.6

var x = <mytree/>;
x.item += <data/>;
x.item += <data/>;
x

//Result:

<mytree>
  <data/>
  <data/>
</mytree>

//Note that .item is not significant.



E4X Query ( like XPath )
Javascript 1.6 // E4X Sorgusu (XPath gibi)

var xml = <mytree>
 <data id="1" text="foo"/>
 <data id="2" text="bar"/>
</mytree>

Print( xml.data.(@id==1).@text );
var myid = 2;
Print( xml.data.(@id==myid).@text );

//prints:

foo
bar

swap two variables Javascript 1.7 // İki değişkenin yerlerini değiştirmek

var a = 1;
var b = 2;
[a,b] = [b,a];



Destructuring assignment with function arguments Javascript 1.7 // Fonksiyona aktarılan değerleri (atamaları) parçalamak

function foo( [a,b] ) {

 Print(a);
 Print(b);
}

foo( [12,34] );

//Prints:

12
34

Javascript scope is not C/C++ scope // Javascript dili C/C++ dili değildir

if ( false ) { // never reach the next line

 var foo = 123;
}

Print(foo); // prints: undefined ( but is defined )
Print(bar); // failed: ReferenceError: bar is not defined



Javascript scope and LET instruction // Javascript dili ve LET talimatı

var x = 5;
var y = 0;
let (x = x+10, y = 12) {
  Print(x+y);
}
Print(x+y);

//prints:

27
5

or,

for ( let i=0 ; i < 10 ; i++ ) {
  Print(i + ' ');
}
Print(i);

//prints:

0 1 2 3 4 5 6 7 8 9 test.js:4: ReferenceError: i is not defined



Defer function calls // Fonksiyon çağrılarını ertelemek

var opList = [];
function deferCall( text, value ) {
 opList.push(arguments)
}
function doCall(func) {
 while (opList.length)
  func.apply(this,opList.shift());
}

deferCall( 'one', 1 );
deferCall( 'titi', 'toto' );
deferCall( 5, 'foo' );

function callLater(a,b) {
 
Print(a+', '+b);
}

doCall( callLater )

//Prints:

one, 1
titi, toto
5, foo



Check if an object is not empty // Bir objenin varlığı veya boş olup olmadığının kontrolü

function isNotEmpty(obj) {
 for ( var tmp in obj )
  return true
}



Insert an array in another array // Bir diziye başka bir diziyi eklemek

var a = [1,2,3,4,5,6]
var b = ['a','b','c']
var insertIndex = 5;

Array.concat( a.splice( 0, insertIndex ), b, a )

//result:

1,2,3,4,5,a,b,c,6



Multiple string concatenation
// Çoklu karakter birleştirimi

var html = ["<html>", "<head>", "<title>"].join("");

//Is faster than:

var html = "<html>" + "<head>" + "<title>";



auto indent Javascript code / unobfuscator // Javascript kodunun otomatik basamaklı yerleşimini sağlamak

//spidermonkey javascript engine only

function foo() { function bar(){};var i=0;for(;i<10;++i) bar(i) }
Print(foo.toSource(2));

//prints:

function foo() {

      function bar() {
      }

      var i = 0;
      for (; i < 10; ++i) {
          bar(i);
      }
  }



Using 'with' scope // 'with' kuşatmasıyla kullanmak (Javascript kodunun otomatik basamakl? yerleşimini sağlamak)

with({ a:5 }) function toto() { return a }
toto() // returns 5

(object).toString() - objeyi karakterlere çevirmek

var a = { toString:function() { return '123'; }  }
Print(a); // prints '123', and not [Object object]

RegExpr.$1 // Karakter parçalama (Regular Expression ile)

var re = /a(.*)/
'abcd'.match(re)
Print( RegExp.$1 ) // prints 'bcd'



Binary with XmlHTTPRequest


var req = new XMLHttpRequest();
req.open('GET', "http://code.google.com/images/code_sm.png",false);
req.overrideMimeType('text/plain; charset=x-user-defined');
//req.overrideMimeType('application/octet-stream');
req.send(null);
var val = req.responseText;
Print( escape(val.substr(0,10)) );

Iterate on values Javascript 1.6 //  Çoklu değerleri ötelemek, sıralı basmak

for each ( var i in [3,23,4] )
 Print(i)

//Prints:

3
23
4

Exceptions Handling / conditional catch (try catch if) // (Taşma, İhlal, Hata) Tutma İşlemi / Şartlı Tutma

function Toto(){}
function Titi(){}

try {

 throw new Titi()

} catch ( err if err instanceof Toto ) {
 Print('toto')
} catch ( err if err instanceof Titi ) {
 Print('titi')
} catch(ex) {
 throw(ex);
}



Special chars // Özel Karakterler

$=4
_=5
Print( _+$)

//prints:

9



eval this // Değerlendirme (Çalıştırarak)

function test() {

 Print(eval('this'));
}
test.call(123)

//prints:

123



No Such Method (noSuchMethod) // Örneklemesiz Metot ( Fonksiyon hatalarını tespit)

var o = {}
o.__noSuchMethod__ = function(arg){ Print('unable to call "'+arg+'" function') }
o.foo(234)

//prints:

unable to call "foo" function



RegExp replace // RegExp (Düzenli-Kurallı İfade) çevirimi

function Replacer( conversionObject ) {

 var regexpStr = '';
 for ( var k in conversionObject )
  regexpStr += (regexpStr.length ? '|' : '') + k;
 var regexpr = new RegExp(regexpStr,'ig'); // g: global, m:multi-line i: ignore case
 return function(s) { return s.replace(regexpr, function(str, p1, p2, offset, s) { var a = conversionObject[str]; return a == undefined ? str : a }) }
}

var myReplacer = Replacer( { '<BR>':'\n', '&amp;':'&', '&lt;':'<', '&gt;':'>', '&quot;':'"' } );

Print( myReplacer('aa<BR>a &amp;&amp;&amp;&lt;') );

//prints:

aa
a &&&<



Values comparaison //Değerleri karşılaştırma

[4] === 4 // is false
[4] == 4 // is true

'0' == 0 // is true
'0' === 0 // is false

//undefined, null, 0, false, '', ... - Tanımsız, yok, 0, yanlış gibi değerlerin kullanımı

var a = { b:undefined, c:null, d:0, f:'' }

a['b'] // is undefined
a['e'] // is undefined

'b' in a // is true
'e' in a // is false

Boolean(a.b) // is false
Boolean(a.c) // is false
Boolean(a.d) // is false
Boolean(a.e) // is false !
Boolean(a.f) // is false

typeof( asvqwfevqwefq ) == 'undefined' // =true



constructor property ( InstanceOf + Type ) //Elemanın objeleşme özelliği

var a = {};
a.constructor === Object // is true



AJAX evaluation //AJAX dönüşümü

var a = {

 b:function() { Print(123) }
}

var body = 'b();';

with(a) { eval(body) };

//prints:

123



Coma operator // Virgül işlemcisi

var a = 0;
var b = ( a++, 99 );

a // is 1
b // is 99

var i = 0;
while( Print('x'), i++<10 )
 Print(i)

//prints:

x
1
x
2
x
3
x
4
x
5
x
6
x
7
x
8
x
9
x
10
x



closures pitfall // Eleman değerini kapsamak ( Değişkenin değerinin değişkenliği)

var a = [];

for ( var i=0; i<10; i++ ) {

 a[i] = function() { Print(i); }
}

a[0](); // is 10
a[1](); // is 10
a[2](); // is 10
a[3](); // is 10

//simpler case:

var i = 5;
function foo() { Print(i) }
foo(); // prints 5
i = 6;
foo(); // prints 6



sharp variable // Kesin değişken

var a = { titi:#1={}, toto:#1# };
a.titi === a.toto; // is true

var a = { b:#1={ c:#1# } }
// a.b.c.c.c.c.c.c...



common object between 2 objects //İki obje arasında kullanılan genel obje

function a() {}

a.prototype = { b:{} }

c = new a;
d = new a;

c.b.e = 2;

c.b === d.b // is true !
d.b.e // is 2

constructor // Kurucu, Sağlamlaştırıcı

function a( b ) {

 Print(b);
}

c.prototype = new a;

function c( arg ) {

 this.constructor.apply( this, arg );
};

o = new c( [1,2,3] );

//prints:

undefined
1



Javascript string can contain null chars // Javascript karakter katarı null(yok) karakterine sahip olabilir.

var test = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00';
test.length // is 10



'new' operator precedence -'new' işlemcisi önceliği

function test() {

 this.toto = 1234;
}

(new test()).toto // ok ( logical way )

new test().toto // ok

new test.toto // bad

(new test).toto // ok



constructor usage

function toto( val ) { // parent class

 this.print = function() {

  Print( val );
 }
}


titi.prototype = new toto;

function titi( val ) { // child class
 
 this.constructor(val);
}

(new titi(7)).print(); // prints 7

To object - objeye çevirme

var obj = Object(123);
obj.foo = 678;
Print( typeof( obj ) + ' : ' + obj + ' : ' + obj.foo );

//prints:

object : 123 : 678



Serialize a variable/object ( can be nested ) // Değer / Obje içeriğini sıral? hale getirme

var o = { a:123, b:'test', c:function() { return 987; } }
Print( o.toSource() );

//prints:

({a:123, b:"test", c:(function () {return 987;})})



Serialize / uneval - Sıralaştırma / Değerlendirilmemiş hale getirme

var obj = { a:123, b:'test', c:function() { return 987; } };
Print( uneval(obj) );

//prints:

({a:123, b:"test", c:(function () {return 987;})})



Javascript labels // Javascript Etiketleri

xxx: {
 Print(111)
 break xxx;
 Print(222)
}

//prints:

111



for in loop // Döngüler için for

for ( var i in function(){ return [1,2,3] }() )
  Print(i)

//prints:

0
1
2

__proto__ ( prototype property ) // Prototip özelliği

var a = {}
var b = {}
a.__proto__ == b.__proto__ // is true



Numbers // Sayılar

(1000000000000000128).toString() // Number( 1000000000000000128 )

Number base conversion ( hexadecimal ) - Say? temeli çevirimi

(255).toString(16); // is ff

parseInt( 'ff', 16 ) // is 255

try / catch / finally

try {

} catch(ex) {

 Print('catch')
} finally {

 Print('finally')
}

//prints:

finally



Object argument // Nesnenin verileri

var proto = {

 x: function() { return 'x' }
}

var o1 = new Object( proto );
var o2 = new Object( proto );

o1 == o2 // is true



object and its prototype // Nesne ve onun prototipi

function obj() {}

obj.prototype = { x:1 };
var b = new obj;

obj.prototype = { x:2 };
var c = new obj;

c.x == b.x // is false

Runtime prototype object  // Çalışma zamanı prototype nesnesi

var proto1 = {
 a:function(){ return 1 }
}

var proto2 = {
 a:function(){ return 2 }
}

function createObject( proto ) {

 var cl = function() {}
 cl.prototype = proto;
 return new cl;
}

var v1 = createObject( proto1 ).a
var v2 = createObject( proto2 ).a

Print( v1() );
Print( v2() );

Print( createObject( proto1 ).a === createObject( proto1 ).a );

//prints:

1
2
true

for in loop and undefined value // Döngüdeki for ve tanımsız değer

var o = { x:undefined }
for ( var i in o )
 Print(i)

//prints:

x

Call function in parent class // Fonksiyonu ana Class ( Fonksiyon kümesi) tan ça??rma

toto.prototype = new function() {

 this.a = function() {

  Print(456)
 }
};


function toto() {

 this.a=function(){

  Print(123)
  toto.prototype.a.call(this); // or: this.__proto__.a();
 }
}

var o = new toto;
o.a();

//prints:

123
456

getter

abcd getter = function() {

 Print(345);
}

abcd;
abcd;
abcd;

//prints:

345
345
345

__defineGetter__ ( define getter )

o = {}
o.__defineGetter__('x', function(){ Print('xxx')} )
o.x

//prints:

xxx

check if an object or its prototype has a propery (hasOwnProperty) // Bir nesnenin prototypenin özelliğinin kontrolü

var o = { a:1 }
o.__proto__ = { b:2 }

o.hasOwnProperty('a'); // is true
o.hasOwnProperty('b'); // is false



check if a property is enumerable (propertyIsEnumerable)

var o = { a:1 }
o.propertyIsEnumerable('a'); // is true

[].propertyIsEnumerable('splice'); // is false



find the getter/setter function of an object ( lookup getter )

function test() {

 this.x getter = function(){ Print('getter') }
 this.x setter = function(){ Print('setter') }
}

var t = new test
t.__lookupGetter__('x')

//prints:

function () {
 Print("getter");
}

//suppress array element while iterating it

//the following example will failed :

var a = [ 0,1,2,3,4,5,6,7,8,9 ];
for ( var i in a ) {

 if ( a[i]==1 || a[i]==2 )
 a.splice( i,1 );
}
Print(a);
Print(a.length);

//We can use : a[i] == undefined; Or start from the end :

var a = [ 0,1,2,3,4,5,6,7,8,9  ];

for ( var i = a.length-1; i>=0; i-- ) {

 if ( a[i]==0 || a[i]==8 )
 a.splice( i,1 );
}
Print(a);
Print(a.length);

javascript arrays // Javascirpt Dizileri

var a = [ 1,2,3 ];
a.x = 'xxx';

for ( var i = 0; i < a.length; i++ )
 Print('a: '+a[i]);

for ( var i in a )
 Print('b: '+a[i]);

//prints:

a: 1
a: 2
a: 3
b: 1
b: 2
b: 3
b: xxx

delete array element // Dizi elemanını silme

//The following do not work:

var ti = [5,6,7,8];
ti.length // is 4
delete ti[3]
ti.length // is 4

Use 'splice' instead:

ti.splice(3,1)
 
 


Yorumunuzu Ekleyin


Yükleniyor...
Yükleniyor...