在一个函数中返回两个变量 [英] Return two variables in one function

查看:169
本文介绍了在一个函数中返回两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码(演示):

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

}

var test = test();

alert(test);

函数test在执行时仅返回第二个值(即'World').如何使其返回多个值?

On execution the function test only returns the second value (i.e. 'World'). How do I make it return multiple values?

推荐答案

您不能从单个函数中显式返回两个变量,但是可以通过多种方式将两个变量连接起来以返回它们.

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.

如果您不需要将变量分开,则可以直接将它们连接起来,如下所示:

If you don't need to keep the variables separated, you could just concatenate them directly like this:

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

这将提醒"HelloWorld". (如果您想在其中留出空间,则应改用var hw = h+" "+w.

This would alert "HelloWorld". (If you wanted a space in there, you should use var hw = h+" "+w instead.

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

If you need to keep the two variables separated, you can place them into an array like so:

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()处理数组的方式(即,按顺序打印数组中每个元素的逗号分隔列表),此处的alert(test)将显示"Hello,World".如果要产生与示例代码相同的输出,则需要使用诸如join()之类的东西. join()将根据数组构造一个字符串,它使用一个参数作为元素之间的分隔符.要重现我的第一个示例中的两个警报,您将需要分别使用alert(test.join(""))alert(test.join(" ").

This allows the h and w values to still be accessed individually as test[0] and test[1], respectively. However, alert(test) here will display "Hello,World" because of the way alert() handles arrays (that is, it prints a comma-separated list of each element in the array sequentially). If you wanted to produce the same output as your example code, you would need use something like join(). join() will construct a string from an array, it takes one argument which serves as a separator between the elements. To reproduce the two alerts from my first example, you would need to use alert(test.join("")) and alert(test.join(" "), respectively.

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

My example could be shortened slightly by skipping the creation of the hw variable and just returning an array directly. In that case, test() would look like this:

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

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

This could also be done as an object with return { h : h, w : w };, in which case you would access the individual variables as test.h and test.w, respectively.

这篇关于在一个函数中返回两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆