2015-08-24 191 views
0

我想寫一個函數來計算單詞的字數,字符數,空格數。我到目前爲止的代碼如下:嵌套函數Javascript字數

function superCounter(str) { 
var chars = str.split("").length; 
var words = str.trim().replace(/\s+/gi, ' ').split(' ').length; 
var spaces = str.split(" ").length - 1; 
}; 

它返回undefined。我知道這個函數裏面有3個其他函數。我怎樣才能得到一個函數來返回其他3個嵌套函數?我覺得我不正常寫這個功能:(

回答

0

你只需要從函數返回對象的最終值(因爲你有一個以上的值返回):

function superCounter(str) { 
 
     var chars = str.length; 
 
     var words = str.trim().replace(/\s+/gi, ' ').split(' ').length; 
 
     var spaces = str.split(" ").length - 1; 
 
     return {spaces: spaces, words: words, chars: chars}; 
 
    }; 
 

 
    var result = superCounter("The quick brown fox jumped over the fence"); 
 
    document.write(result.chars + "<br>"); 
 
    document.write(result.words + "<br>"); 
 
    document.write(result.spaces + "<br>");