最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

possible to return a value from Javascript function parameter? - Stack Overflow

programmeradmin2浏览0评论

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?

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

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

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?

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

function sayHello(name, retVal) {
    retVal = "hello " + name;
    return 1;
}
Share Improve this question asked Jul 3, 2013 at 1:47 zhongzhuzhongzhu 3272 gold badges4 silver badges15 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

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.

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.

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):

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

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

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 &"

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

发布评论

评论列表(0)

  1. 暂无评论