Javascript calling a function that returns two values but I want only the first (or the second)

StackOverflow https://stackoverflow.com/questions/17899871

  •  04-06-2022
  •  | 
  •  

Pergunta

I have a function in javascript that returns two values:

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return [day, dayW];
}

When I call this function (within another function) I whant only one of this values.

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

I know it's a very basic and newbie question. But how do I do that?

Foi útil?

Solução 2

You can return them in an object literal

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 };
}

and access like this

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

or you can return the values in an array:

function today_date() {
  var t = new Date();
  var day = t.getUTCDay();
  var dayW = t.getDay(); // Day of de week (0-6).      
  return [ day, dayW ];
}

and then access the first one like this

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

Outras dicas

Does that actually return 2 values? That's a new one to me. Anyhow, why not do this?

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

and then:

console.log("Today is the " + today_date().day + " of the month.");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top