简体   繁体   English

Javascript:从不同的函数返回多个值

[英]Javascript: return multiple values from different functions

I am trying to return multiple values from different functions. 我试图从不同的函数返回多个值。 The starting point is a bidimensional array. 起点是二维数组。 An example of the code is: 该代码的示例是:

var items = [[0,1],[1,2],[0,2]];
var a;
var b;

function first() {
a = items[Math.floor(Math.random() * items.length)];
return a;
}

function second() {
b = a[Math.floor(Math.random() * 2)];
return b;
}

function third (){
  first();
  second();
}

third();

If I write the code outside the functions, everything works fine. 如果我在函数外部编写代码,则一切正常。 When I use functions and replace return with console.log, it works. 当我使用函数并用console.log替换return时,它可以工作。 If I use functions and return (as in the code reported above), it gives me undefined. 如果我使用函数并返回(如上面报告的代码中所示),它将使我不确定。 I didn't find solutions. 我没有找到解决方案。 Why the code isn't working? 为什么代码不起作用?

Thanks in advance 提前致谢

If you are declaring variable a and b outside function(like in your code) than there is no need to return the values. 如果在函数外声明变量a和b(就像在代码中一样),则无需返回值。 a and b will get defined. a和b将被定义。 But if you are not declaring it outside, then store the return values in array variable. 但是,如果您未在外部声明它,则将返回值存储在数组变量中。

var items = [[0,1],[1,2],[0,2]];

function first() {
a = items[Math.floor(Math.random() * items.length)];
return a;
}

function second() {
b = a[Math.floor(Math.random() * 2)];
return b;
}

function third (){
var a = first();
var b = second();
var arr  = [];
arr.push(a);
arr.push(b);
return arr 
}

var t = third();
console.log(t[0], t[1]);

If you want third to return values, add a return in it. 如果要让第三个返回值,请在其中添加一个返回值。

function third (){
  var a = [];
  a.push(first())
  a.push(second())
  return a;
}

Maybe you want something like 也许你想要类似的东西

function third (){
  return {a: first(), b: second()};
}

then 然后

var t = third()
console.log(t.a, t.b)

or if you're running on ES6 或者如果您在ES6上运行

var {a,b} = third()
console.log(a, b)

see Destructuring assignment for further details 请参阅解构分配以获取更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM