如何在Javascript中为变量分配return语句?

时间:2020-03-11 15:34:22

标签: javascript return var

var robotLeaves = "The robot has left to get milk!"
var byeRobot = return robotLeaves;

我试图通过使用return语句显示分配给robotLeaves变量的内容。另外,我正在尝试将该return语句分配给变量,以便我可以重用它。

哪个网站||我应该签出资源以找到解决方案,以解决此问题吗?

编辑: 这是我正在尝试的完整代码:

function getMilk() {
  var shop = 10;
  var robotLeaves = "The robot has left to get milk!"
  var robotReturns = "The robot has come back with 1 bottle of milk!"
  var byeRobot = return robotLeaves;

  byeRobot;
  if(byeRobot) {
    --shop;
    return robotReturns;
    return shop;
  };
}
getMilk();

第二次编辑: 原来我在错误地使用return语句!感谢所有发布者!

2 个答案:

答案 0 :(得分:1)

没有冒犯,但是您想做的很奇怪。 return不像为您提供值的函数或变量,它仅接受值。您将其放在函数中,然后返回的内容就是您以后使用该函数时所得到的。它始终是函数要做的最后一件事,当它返回时,它将停止执行。因此return不会显示任何内容,但是您可以将返回的任何值传递给确实起作用的函数。

function getRobotState() {
  return "The robot has left to get milk!";
}

var robotLeaves = getRobotState();//Run the function, retrieve whatever it returns, put it in a variable so you can reuse it.
//Display value
console.log(robotLeaves)
//You can use robotLeaves as many times as you want from here downwards.
postOnTwitter("Where is the robot? " + robotLeaves)

答案 1 :(得分:1)

我认为您正在尝试做类似的事情?

var shop = 10;

function getMilk() {
  var robotLeaves = "The robot has left to get milk!"
  var robotReturns = "The robot has come back with 1 bottle of milk!"

  --shop;
  console.log(robotReturns);
  console.log(shop);
}

getMilk();