JavaScript:如何从一个函数返回两个值并在另一个函数中调用这两个变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29044427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:00:14  来源:igfitidea点击:

JavaScript: How do I return two values from a function and call those two variables in another function?

javascriptfunctionparsingreturn

提问by mincedMinx

JavaScript:

JavaScript:

                function getValue(){
                    var num1 = document.getElementById("firstNum").value;
                    var num2 = document.getElementById("secondNum").value;

                    return (num1, num2);
                }

                function add(){
                    getValue();

                    var result = parseFloat(num1) + parseFloat(num2);

                    return result;
                }

What I'm creating is a calculator that gets the values from input boxes. What I'm having trouble with is how am I supposed to call the variables I declare in the getValue(); function in my add(); function to create a value.

我正在创建的是一个计算器,它从输入框中获取值。我遇到的问题是我应该如何调用我在 getValue(); 中声明的变量;我的 add() 中的函数;创造价值的功能。

I appreciate the help.

我很感激你的帮助。

回答by jfriend00

You can't return two values like this:

你不能像这样返回两个值:

return (num1, num2);

Javascript doesn't work that way. If you're trying to do a Python-like tuple, Javascript doesn't have a data structure with that syntax.

Javascript 不能那样工作。如果您正在尝试执行类似 Python 的元组,则 Javascript 没有具有该语法的数据结构。

You can put two values in an array and return the array or two values in an object and return the object.

您可以将两个值放入一个数组并返回该数组或一个对象中的两个值并返回该对象。

And, then when you call the function, you have to assign the result to something in order to use the returned result.

然后,当您调用该函数时,您必须将结果分配给某些东西才能使用返回的结果。

Here's one way returning an array:

这是返回数组的一种方法:

function getValues(){
    var num1 = document.getElementById("firstNum").value;
    var num2 = document.getElementById("secondNum").value;
    // return array of two values
    return [num1, num2];
}

function add(){
   // get values and assign the returned array to a local variable named values
   var values = getValues();
   return parseFloat(values[0]) + parseFloat(values[1]);
}

Or, you could put both values into an objectwith named properties:

或者,您可以将两个值放入具有命名属性的对象中

function getValues(){
    var num1 = document.getElementById("firstNum").value;
    var num2 = document.getElementById("secondNum").value;
    // return array of two values
    return {firstNum: num1, secondNum: num2};
}

function add(){
   // get values and assign the returned array to a local variable named values
   var values = getValues();
   return parseFloat(values.firstNum) + parseFloat(values.secondNum);
}

The object syntax is more descriptive and verbose because each property has a relevant name rather than just a numeric index, but it's also less compact. In this particular case, you could use either the object or the array.

对象语法更具描述性和详细性,因为每个属性都有一个相关的名称而不仅仅是一个数字索引,但它也不太紧凑。在这种特殊情况下,您可以使用对象或数组。

ES6 Destructuring Update

ES6 解构更新

When returning two values in an array or an object, you can also use ES6 syntax to shorten the code to do that. For example, when returning an object, you can use the shorthand syntax that assigns the property name as the same name as the variable as in:

当在数组或对象中返回两个值时,您还可以使用 ES6 语法来缩短代码来实现这一点。例如,当返回一个对象时,您可以使用速记语法,将属性名称分配为与变量相同的名称,如下所示:

return {num1, num2};

This actually returns an object that is like this:

这实际上返回了一个像这样的对象:

{ num1: num1, num2: num2 }

And, then when you call that function, you can use destructuring to assign both values to variables:

然后,当您调用该函数时,您可以使用解构将两个值分配给变量:

function getValues(){
    var num1 = document.getElementById("firstNum").value;
    var num2 = document.getElementById("secondNum").value;
    // return array of two values
    return {num1, num2};
}

let {num1, num2} = getValues();
console.log(num1);
console.log(num2);

Or, you can use destructuring similarly with an array:

或者,您可以类似地对数组使用解构:

function getValues(){
    var num1 = document.getElementById("firstNum").value;
    var num2 = document.getElementById("secondNum").value;
    // return array of two values
    return [num1, num2];
}

let [num1, num2] = getValues();
console.log(num1);
console.log(num2);

回答by VIN

In ECMAScript 6 (ES6), you can use object destructuring, using braces to create and unpack objects (it looks like a tuple in your case). You can also make use of the property value shorthand available in ES6:

在 ECMAScript 6 (ES6) 中,您可以使用对象解构,使用大括号来创建和解包对象(在您的情况下它看起来像一个元组)。您还可以使用 ES6 中可用的属性值速记:

const getValues = () => {
  const num1 = document.getElementById("firstNum").value;
  const num2 = document.getElementById("secondNum").value;
  return { num1, num2 }; //note that this is the property value shorthand. 
  // It is a shorthand for { num1: num1, num2: num2 }
}

const add = () => {
  const { num1, num2 } = getValue(); //unpack using object destructuring
  return parseFloat(num1) + parseFloat(num2);
}

More information here: http://www.benmvp.com/learning-es6-enhanced-object-literals/

更多信息在这里:http: //www.benmvp.com/learning-es6-enhanced-object-literals/

回答by sebnukem

Simply return an object! Objects are one of the things that make JavaScript so powerful.

只需返回一个对象!对象是使 JavaScript 如此强大的因素之一。

function getValue() {
  return {
     firstNum:  document.getElementById("firstNum").value,
     secondNum: document.getElementById("secondNum").value
  };
}

function add() {
   var values = getValue();
   var result = parseFloat(values.firstNum) + parseFloat(values.secondNum);
   return result;
}

回答by Tony

If those two returned values are going to be used by another function, then use them as parameters to the second function.

如果这两个返回值将被另一个函数使用,则将它们用作第二个函数的参数。

function getValue(){

    var num1 = document.getElementById("firstNum").value;
    var num2 = document.getElementById("secondNum").value;

    //return (num1, num2);
    //instead of returning the values, use them immediately to the consuming method
    var addedNumbers = add(num1, num2);
    return addedNumbers;
}

function add(num1, num2){

    var result = parseFloat(num1) + parseFloat(num2);

    return result;
}

Going back to your question, you cannot return two variables as a result of a function, unless you are returning it as Array.

回到你的问题,你不能作为函数的结果返回两个变量,除非你将它作为数组返回。

回答by Gabriele Petrioli

Try returning an array (as you can only return one value from a function)

尝试返回一个数组(因为您只能从函数中返回一个值

  function getValue() {
    var num1 = document.getElementById("firstNum").value;
    var num2 = document.getElementById("secondNum").value;

    return [num1, num2];
  }

  function add() {
    var values = getValue(),
        result = parseFloat(values[0]) + parseFloat(values[1]);

    return result;
  }

回答by Thi Tran

You can return an object and get its value in add function

您可以返回一个对象并在 add 函数中获取其值

function getValue(){
  var num1 = document.getElementById("firstNum").value;
  var num2 = document.getElementById("secondNum").value;

  return {num1: num1, num2: num2};
}

function add(){
  var obj = getValue();

  var result = parseFloat(obj.num1) + parseFloat(obj.num2);

  return result;
}

回答by LeFex

You could put your variables into a neat little object, like so:

您可以将变量放入一个整洁的小对象中,如下所示:

return {num1: num1, num2: num2};

Then:

然后:

var values = getValue();

var result = parseFloat(values.num1) + parseFloat(values.num2);

And so on..

等等..

回答by PM 77-1

You do notneed to return multiple values in your code.

不是需要在你的代码返回多个值。

           function getValue(ID){
                return document.getElementById(ID).value;
            }

            function add(){
                var result = parseFloat(getValue("firstNum")) + 
                             parseFloat(getValue("secondNum"));

                return result;
            }

The above code will fail if either of the IDs does not exist but so will yours.

如果其中一个 ID 不存在,则上述代码将失败,但您的也会失败。

回答by what

I think Javascript only supports multiple return values as global variables with destructuring, so its not recommended. However you can return an array and then destructur that array, its a bit of a inconvenience, however it does the same thing.

我认为 Javascript 只支持多个返回值作为具有解构的全局变量,所以不推荐。但是,您可以返回一个数组,然后解构该数组,这有点不方便,但是它可以做同样的事情。

          // global multiple returns
     function getValues(){
           let values=[]; 
            values.push(document.getElementById("firstNum").value);
           values.push(num2 = document.getElementById("secondNum").value);
          // return array of two values
          return [num1, num2]=values;
        }
         //recommended way without global variables requiring destructuring outside of function
            function getValue(){
                 let values=[];
                 values.push(document.getElementById("firstNum").value);
                values.push(document.getElementById("secondNum").value);

                return values ;
            }

           let[num1,num2]=getValues();//breaks array into multiple variables

      function add(){
                getValue();

                var result = parseFloat(num1) + parseFloat(num2);

                return result;
            }