【问题标题】:Return two variables in one function [duplicate]在一个函数中返回两个变量[重复]
【发布时间】:2013-11-13 07:54:24
【问题描述】:

考虑以下代码 (demo):

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

}

var test = test();

alert(test);

在执行时,函数test 只返回第二个值(即'World')。如何让它返回多个值?

【问题讨论】:

标签: javascript function


【解决方案1】:
function test(){ 
  var h = 'Hello'; 
  var w = 'World'; 
  return {h:h,w:w}
}

var test = test();

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

一种简单的方法是返回包含多个键值对的对象。

【讨论】:

  • 如果函数参数中有实参怎么办?
【解决方案2】:

您不能从单个函数显式返回两个变量,但有多种方法可以连接两个变量以返回它们。

如果您不需要将变量分开,您可以像这样直接连接它们:

function test(){
  var h = 'Hello';
  var w = 'World';
  var hw = h+w 
  return (hw);
}
var test = test();
alert(test);

这会提醒“HelloWorld”。 (如果你想要一个空间,你应该改用var hw = h+" "+w

如果您需要将两个变量分开,您可以将它们放入一个数组中,如下所示:

function test(){
  var h = "Hello";
  var w = "World";
  var hw=[h,w];
  return hw;
}
var test = test();
alert(test);

这允许hw 值仍分别作为test[0]test[1] 单独访问。但是,这里的 alert(test) 将显示“Hello,World”,因为 alert() 处理数组的方式(即,它按顺序打印数组中每个元素的逗号分隔列表)。如果您想产生与示例代码相同的输出,则需要使用类似join() 的内容。 join() 将从数组构造一个字符串,它采用一个参数作为元素之间的分隔符。要重现我的第一个示例中的两个警报,您需要分别使用 alert(test.join(""))alert(test.join(" ")

通过跳过hw 变量的创建并直接返回一个数组,可以稍微缩短我的示例。在这种情况下, test() 看起来像这样:

function test(){
  var h="Hello";
  var w="World";
  return [h, w];
}

这也可以作为return { h : h, w : w }; 的对象来完成,在这种情况下,您可以分别以 test.h 和 test.w 的形式访问各个变量。

【讨论】:

    【解决方案3】:

    comma operator 计算每个操作数,然后返回最后一个的值。

    您需要返回一个数组:

    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
    

    【讨论】:

      【解决方案4】:

      您可以返回一个数组或一个新对象。

      【讨论】:

        猜你喜欢
        • 2013-02-28
        • 2015-06-22
        • 1970-01-01
        • 2018-03-26
        • 1970-01-01
        • 2012-11-21
        • 2016-03-16
        • 2013-12-08
        • 2015-05-16
        相关资源
        最近更新 更多