function return two values
I want to ask how effective is this function and if there are any situa开发者_如何学JAVAtions when I can use it. Thanks for any answers.
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>");
It might be more useful to use an object as a return value, instead of a string.
return { sum: c, diff: d };
This way, you can easily use it by typing result.sum
or result.diff
.
If you need to return more than one value, you're pretty much looking at an array or object:
function sum_and_diff(a, b) {
…
return { sum : c, diff : d };
}
var foo = sum_and_diff(1, 2);
alert(foo.sum);
alert(foo.diff);
精彩评论