2012-07-04 72 views
1

我有一个函数,我正试图优化当前,但我遇到了一些问题。内联if语句并返回

该函数将被调用很多次,所以我试图使返回的值很快确定并且下一个调用开始。

(通过迅速确定我的意思是不具有该功能的尾单return声明。)

这是简化的代码:

function myFunction(letr) { 
    if (letr === " ") return var letc = " "; 
    // ... other checks on letr that will return other values for letc 
} 

的问题是,二号线没有按”似乎是有效的JavaScript。

这怎么写出正确的方式+优化?

预先感谢您!

+0

您可以使用三元运算符来优化你的函数 –

+0

@Nudier你不能'从三元return' ... :) – xandercoded

+1

为什么你需要letc变量?为什么不简单地做一个'return'“'? – hugomg

回答

5

不要声明一个变量的结果,只是返回的值。例如:

function myFunction(letr) { 
    if (letr === " ") return " "; 
    if (letr === "x") return "X"; 
    if (letr === "y") return "Y"; 
    return "neither"; 
} 

您还可以使用条件运算符:

function myFunction(letr) { 
    return letr === " " ? " " : 
    letr === "x" ? "X" : 
    letr === "y" ? "Y" : 
    "neither"; 
} 
2
function myFunction(letr) { 
    if (letr === " ") return { letc : " " }; 

    // ... other checks on letr that will return other values for letc 
} 
+0

Oh ok thx !我认为在一个“单行”if语句中,你不必使用{和}? –

+0

我认为这将返回一个属性为''''''''''的'letc'对象。 – Zhihao

+0

@ hi昊的确如此,如果不是'对象'引用,什么是var? – xandercoded

0

一旦返回,该功能将被终止并获得价值出来来电

function myFunction(letr) { 
    var letc = " "; 
    //Do some thing wit letc; 
    if (letr === " ") return letr ; 
    // ... other checks on letr that will return other values for letc 
}