javascript - Fonksiyondan erken çıkış?


Bir fonksiyonum var:

function myfunction() {
  if (a == 'stop')  // How can I stop the function here?
}

JavaScript'te exit() gibi bir şey var mı?

Cevap #1

Sadece return kullanabilirsiniz.

function myfunction() {
     if(a == 'stop') 
         return;
}

Bu, fonksiyonu çağıran herhangi bir şeye undefined döndürme değerini gönderecektir.

var x = myfunction();

console.log( x );  // console shows undefined

Elbette, farklı bir dönüş değeri belirtebilirsiniz. Hangi değer döndürülürse, yukarıdaki örnekte olduğu gibi konsola kaydedilecektir.

return false;
return true;
return "some string";
return 12345;

Cevap #2

Görünüşe göre bunu yapabilirsin:

function myFunction() {myFunction:{
    console.log('i get executed');
    break myFunction;
    console.log('i do not get executed');
}}

Bir etiketi kullanarak blok kapsamlarını görün: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

Henüz herhangi bir olumsuz yön göremiyorum. Ama bu, yaygın bir kullanım gibi görünmüyor.

Bu cevabı türettim: PHP’nin die fonksiyonunun JavaScript karşılığı

Cevap #3

function myfunction() {
     if(a == 'stop') 
         return false;
}

return false;, sadece return; demekten çok daha iyidir

Cevap #4

Bu :

function myfunction()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}

Cevap #5

Biraz farklı bir yaklaşım kullanarak, try catch ve throw ifadesini kullanabilirsiniz.

function name() {
    try {
        ...

        //get out of here
        if (a == 'stop')
            throw "exit";

        ...
    } catch (e) {
        // TODO: handle exception
    }
}

İlgili makaleler