次のコードを考えてみましょう ( demo ):
function test(){
var h = 'Hello';
var w = 'World';
return (h, w);
}
var test = test();
alert(test);
実行時に、関数test
は 2 番目の値 (つまり'World'
) のみを返します。複数の値を返すようにするにはどうすればよいですか?
次のコードを考えてみましょう ( demo ):
function test(){
var h = 'Hello';
var w = 'World';
return (h, w);
}
var test = test();
alert(test);
実行時に、関数test
は 2 番目の値 (つまり'World'
) のみを返します。複数の値を返すようにするにはどうすればよいですか?
function test(){
var h = 'Hello';
var w = 'World';
return {h:h,w:w}
}
var test = test();
alert(test.h);
alert(test.w);
簡単な方法の 1 つは、複数のキーと値のペアを含むオブジェクトを返すことです。
コンマ演算子は各オペランドを評価し、最後のオペランドの値を返します。
配列を返す必要があります。
return [h, w];
...またはオブジェクト:
return { h : h, w : w };
次に、次のように使用します。
var test = test();
alert(test[0]); // "hello" - in the case of the array version
...また:
var test = test();
alert(test.w); // "world" in the case of the object version
配列または新しいオブジェクトを返すことができます。