Javascript Language Tips & Tricks

Javascriptle İlgili İpuçları ve Püf Noktaları

Javascript Language Tips & Tricks

Check for an empty/undefined/null string in JavaScript?
if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}

 

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 - IndexOf() ve lastIndexOf() fonksiyonlar?n?n bir dizide çal??t?r?lmas?

Javascript 1.6

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

returns:

2

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

Javascript 1.7

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 - yield i?lemcisini kullanarak fonksiyona benzeyen parçalar? üretmek

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 - 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 = ;
x.item += ;
x.item += ;
x

Result:


 
 

Note that .item is not significant.

E4X Query ( like XPath ) - E4X Sorgusu (XPath gibi)

Javascript 1.6

var xml =
 
 

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

prints:

foo
bar

swap two variables - ?ki de?i?kenin yerlerini de?i?tirmek

Javascript 1.7

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

Destructuring assignment with function arguments - Fonksiyona aktar?lan de?erleri (atamalar?) parçalamak

Javascript 1.7

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 = ["

", "", "

Is faster than:

var html = "

" + "" + "

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. - Karakter parçalama (Regular Expression ile)

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

Binary with XmlHTTPRequest - XmlHTTPRequest ile Binary ça?r?mlar

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 - Çoklu de?erleri ötelemek, s?ral? basmak

Javascript 1.6

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

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( { '
':'n', '&amp;':'&', '&lt;':'<', '&gt;':'>', '&quot;':'"' } );

Print( myReplacer('aa
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

links

obligated lecture to understand closures

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 = 'x00x00x00x00x00x00x00x00x00x00';
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 - Kurucu, Sa?lamla?t?r?c? kullan?m?

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? prototip 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ön?ü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)

 

 

Form eleman?n de?erini kontrol

function ValidateForm(form)
{

   if(IsEmpty(form.account_number))
   {
      alert('You have not entered an account number')
      form.account_number.focus();
      return false;
   }
 
 
   if (!IsNumeric(form.account_number.value))
   {
      alert('Please enter only numbers or decimal points in the account field')
      form.account_number.focus();
      return false;
      }
 
return true;
 
}

 

 

 

 

Yorumunuzu Ekleyin


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