簡體   English   中英

這是在javascript中調用函數的正確方法嗎?

[英]Is this the right way to call a function in javascript?

這是我的文檔的一部分:

function MyFunction() {
    var x=""

    if (x=1) {
        OnBtnPbDemo_SwitchChn1(1); //This is a function
    } else {
        OnBtnPbDemo_SwitchChn1(0); //This is another function
    }
}

我想知道這是否是在條件內調用函數的正確方法。
非常感謝你。

是的,無論您在何處調用函數,調用函數都是相同的。

您需要在if條件中使用==而不是使用=

 if (x==1) {

代替

 if (x=1) {

如果要為不同的x值調用相同的函數,請嘗試以下操作

  function MyFunction() {
       var x = 1;   
       OnBtnPbDemo_SwitchChn1(x); //you can pass the x value directly to that function.         
    }

如果您要針對不同的x值調用其他函數,請嘗試以下操作

  function MyFunction() {
    var x="";
        if (x==1) {
            OnBtnPbDemo_SwitchChn1(1); //This is a function
        } else {
            OnBtnPbDemo_SwitchChn1_another(0); //This is another function
        }
    }

不能完全確定“正確”調用方式的含義,但是只要范圍內可用,就可以調用函數。

您實際上也可以縮短您為此寫的內容:

function MyFunction () {
    var x = "";
    OnBtnPbDemo_SwitchChn1(x === 1 ? 1 : 0);
}

除非您實際上在函數內部更改x變量,否則它將永遠不會以1作為參數運行。

您將調用同一函數兩次,而只需使用值1/0調用一次函數。

function MyFunction() {
//Check and find value of x
if(x=="somevalue") //true condition
{
   x=1;
}
else{
x=0;
}
OnBtnPbDemo_SwitchChn1(x);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM