简体   繁体   中英

How can I return two parameters from a javascript function?

I have the following:

function getPk(entity) {
    var store = window.localStorage;
    switch (entity) {
        case "City":
            if (store.getItem('AccountID')) {
                // Need to return both of the below pieces of information
                return store.getItem('AccountID') + "04" + "000";
                return "CityTable";

            } else {
                paramOnFailure("Please reselect"); 
                return false;
            }
            break;

The problem is I need to be able to call this function and return two strings. Here I show two return statements but I know I cannot do that.

Is there a clean way I can return two strings to the function that calls my getPk(entity) function?

If possible can you give an example also of how I can read what is returned.

Return them as either an array, or within an object.

return [store.getItem('AccountID') + "04" + "000", "CityTable"];

or

return { accountID: store.getItem('AccountID') + "04" + "000", table: "CityTable" };

You can only return a single value from a function in JavaScript, but that value can be a structure that contains multiple values internally, such as an array:

return [store.getItem('AccountID') + "04" + "000", "CityTable"];

Just make sure that the functions which call this know about the conventions you're using for your return value.

In javascript and like almost every languages, It is impossible to return more than one value.

However, you can return a custom object containing all the values you want to return.

See the following link to find how to create an object. Create an object with properties,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM