24

次のコードを考えてみましょう ( demo ):

function test(){
   var h = 'Hello';
   var w = 'World';
   return (h, w);

}

var test = test();

alert(test);

実行時に、関数testは 2 番目の値 (つまり'World') のみを返します。複数の値を返すようにするにはどうすればよいですか?

4

4 に答える 4

19
function test(){ 
  var h = 'Hello'; 
  var w = 'World'; 
  return {h:h,w:w}
}

var test = test();

alert(test.h);
alert(test.w);

簡単な方法の 1 つは、複数のキーと値のペアを含むオブジェクトを返すことです。

于 2013-11-02T02:10:39.273 に答える
13

コンマ演算子は各オペランドを評価し、最後のオペランドの値を返します。

配列を返す必要があります。

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
于 2013-11-02T02:11:10.167 に答える
3

配列または新しいオブジェクトを返すことができます。

于 2013-11-02T02:05:51.447 に答える