2011-02-15 129 views
1

我想問一下這個函數的有效性,以及是否有什麼情況可以使用它。感謝任何答案。函數返回兩個值

function sum_and_dif(a, b) { 
    var c = a + b; 
    var d = a - b; 
    return c +" " + d; 
} 

var result = sum_and_dif (200, 10); 

document.write(result +"</br>"); 

var where_is_a = result.indexOf(" ");// Here i detected where is the empty space 
var c_number = parseInt(result.substring(0, where_is_a)); 
var d_number = parseInt(result.substring(where_is_a +1,result.length)); 

document.write(c_number +"</br>"); 
document.write(d_number +"</br>"); 

回答

5

將對象用作返回值而不是字符串可能更有用。

return { sum: c, diff: d }; 

這樣,您就可以輕鬆地通過鍵入result.sumresult.diff使用它。

+0

感謝,我更這裏[鏈接](HTTP讀取。 com/library/blmultir.htm) – joni 2011-02-15 11:44:37

2

如果需要返回多個值,你幾乎看一個數組或對象://javascript.about:

function sum_and_diff(a, b) { 
    … 
    return { sum : c, diff : d }; 
} 

var foo = sum_and_diff(1, 2); 
alert(foo.sum); 
alert(foo.diff);