2017-02-09 102 views
0

我想創建一個接受數組的函數。如果數組爲空(或=== 0),我想返回一個字符串。如果數組不爲空,我想返回一個不同的字符串+ remove +返回數組的第一個元素。我該如何做到這一點?2函數返回值取決於if語句嗎? (JS)

樣品

> function(ary) { 
> if (ary.length === 0) { 
>-return string- 
>} 
>else {return other string + ary.shift[0]} 
>} 
+0

的代碼似乎是罰款。你遇到什麼問題? – MaxZoom

+0

而問題是? – John3136

+0

@MaxZoom在任何情況下,我都沒有找到其他人,它只是返回了第一個字符串。 – jsc42

回答

1

下面是你的代碼與一個shift修正:

function check(ary) { 
 
    if (ary.length === 0) { 
 
    return "empty"; 
 
    } else { 
 
    return "First was the " + ary.shift() 
 
    } 
 
} 
 

 
console.log(check([])); 
 
console.log(check(['word', 'chaos', 'light']));

1

shift是拿不出參數的函數。它應該被稱爲是這樣的:

function(ary) { 
    if (ary.length === 0) { 
     return "string"; 
    } 
    else { 
     return "other string" + ary.shift(); 
    } 
} 

注意else可以被刪除。只要返回表明就足夠了,因爲如果ary的長度爲0,那麼將永遠不會達到if之後的代碼(因爲if正文中的return),所以後面的代碼可能由else解包。就像這樣:

function(ary) { 
    if (ary.length === 0) // remove the braces as well since the `if` body is just one statement 
     return "string"; 
    return "other string" + ary.shift(); // if `if`'s test is true this line will never be reached 
}