【问题标题】:How do I assign a return statement to a variable in Javascript? [closed]如何将 return 语句分配给 Javascript 中的变量? [关闭]
【发布时间】:2020-03-11 15:34:22
【问题描述】:

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

我正在尝试使用 return 语句来显示分配给 robotsLeaves 变量的内容。此外,我正在尝试将该 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语句!感谢所有发帖的人!

【问题讨论】:

  • 我不确定我是否理解您在此处返回的意思,因为变量已经定义。 return 用于函数
  • return 仅适用于函数。你的周边功能在哪里?
  • 返回语句需要使用函数
  • “重用”是什么意思?你想如何重复使用它?
  • 为什么不简单地 var byeRobot = robotLeaves 呢?另外为什么不直接使用robotLeaves

标签: javascript return var


【解决方案1】:

无意冒犯,但您尝试做的事情很奇怪。 return 不像给你一个值的函数或变量,它只接受值。你把它放在一个函数中,无论你返回什么都是你以后使用这个函数时得到的。它总是一个函数做的最后一件事,当它返回时,它停止执行。所以return 不显示任何内容,但您可以将返回的任何值传递给 DOES 的函数。

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)

【讨论】:

    【解决方案2】:

    我认为你正在尝试做这样的事情?

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-02
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      相关资源
      最近更新 更多