可以从 Javascript 函数参数返回一个值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17438475/
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-27 08:19:09  来源:igfitidea点击:

possible to return a value from Javascript function parameter?

javascript

提问by zhongzhu

I'd like my function to return both an error code and a string value, so plan to use return to return the error code and use a parameter to return the string value. But it doesn't work. Looks like we can't return a value from function parameter. Any idea how to return it from function parameter?

我希望我的函数同时返回错误代码和字符串值,因此计划使用 return 返回错误代码并使用参数返回字符串值。但它不起作用。看起来我们不能从函数参数返回一个值。知道如何从函数参数返回它吗?

Below is a sample code. I hope to get the retVal from sayHello's parameter.

下面是一个示例代码。我希望从 sayHello 的参数中得到 retVal。

function sayHello(name, retVal) {
    retVal = "hello " + name;
    return 1;
}

回答by PSL

You can probably do this way, pass an object back.

您可能可以这样做,将对象传回。

function sayHello(name) {

    retVal = "hello " + name;
    return {code: 1, message: retVal};
}

//And while calling
var returnVal= sayHello("something");
var code = returnVal.code;
var msg= returnVal.message;

Reason why retVal is nt available outside is because of variable hoisting in the scope inside the function. But you can also work around that by not passing it in as argument.

retVal 在外部不可用的原因是因为函数内部作用域中的变量提升。但是您也可以通过不将其作为参数传递来解决这个问题。

var retVal; //Define it in an outer scope.
function sayHello(name) {
    retVal = "hello " + name;
    return 1;
}
var returnVal= sayHello("something");
alert(returnVal);
alert(retVal); //Now get it here.

回答by Paul

PSL's solution is the best, but if you really want to know how to return it through an argument, the only way is to use an object, since object's are passed by reference, not copied (Note that arrays are objects):

PSL 的解决方案是最好的,但如果你真的想知道如何通过参数返回它,唯一的方法是使用对象,因为对象是通过引用传递的,而不是复制的(注意数组是对象):

var hello = [];
sayHello("Paul", hello); // "hello[0] === "hello Paul"

function sayHello(name, retVal) {
    retVal[0] = "hello " + name;
    return 1;
}

回答by Liang Qi

Your question is still not valid for JavaScript. Current question is still same or similar with your previous one, QtScript can't call function with argument type "QString &"

您的问题对 JavaScript 仍然无效。当前问题与您之前的问题仍然相同或相似,QtScript 无法调用参数类型为“QString &”的函数

What you need is just google "return multiple values in javascript", like Returning multiple values in javascript?

你需要的只是谷歌“在javascript中返回多个值”,比如在javascript中返回多个值?