Javascript调用一个返回两个值的函数,但我只需要第一个(或第二个)

Javascript调用一个返回两个值的函数,但我只需要第一个(或第二个),javascript,function-calls,Javascript,Function Calls,我有一个javascript函数,返回两个值: function today_date() { var t = new Date(); var day = t.getUTCDay(); var dayW = t.getDay(); // Day of de week (0-6). return [day, dayW]; } 当我调用这个函数(在另一个函数中)时,我只调用其中一个值 function print_anything() { console.log("

我有一个javascript函数,返回两个值:

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return [day, dayW];
}
当我调用这个函数(在另一个函数中)时,我只调用其中一个值

function print_anything() {
  console.log("Today is the " + today_date() + " of the month.");
}

我知道这是一个非常基本的新手问题。但是我该怎么做呢?

这真的会返回2个值吗?这对我来说是新的。无论如何,为什么不这样做呢

return {'day': day, 'dayW': dayW };
然后:

console.log("Today is the " + today_date().day + " of the month.");

您可以在对象文本中返回它们

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return { "day" : day, "dayOfWeek" : dayW };
}
像这样的访问

function print_anything() {
  console.log("Today is the " + today_date().day + " of the month.");
}
function print_anything() {
  console.log("Today is the " + today_date()[0] + " of the month.");
}
也可以返回数组中的值:

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return [ day, dayW ];
}
然后像这样访问第一个

function print_anything() {
  console.log("Today is the " + today_date().day + " of the month.");
}
function print_anything() {
  console.log("Today is the " + today_date()[0] + " of the month.");
}

为什么不使用两个不同的函数呢?返回语句的作用与您认为的不同。更具体地说,canon刚才说的是,您的函数只返回dayW。如果执行
返回stuff1,stuff2同时计算
stuff1
stuff2
,但只返回
stuff2
。简单到+1wiw,return语句不返回2个值。它只是逗号运算符;返回语句中的最后一个值。TLDR,只返回最后一条语句。最好使用“点表示法”