简体   繁体   中英

Return multiple variables from a JavaScript function?

In python, to return multiple variables, I can do --

def function_one(i):
    return int(i), int(i) * 2

value, duble_value = function_one(1)

How would I achieve this same result using javascript if functions may only return a single return value? (I assume using an array?)

You need to either use an array or an object.

For example:

function test() {
    return {foo: "bar", baz: "bof"};
}

function test2() {
    return ["bar", "bof"];
}

var data = test();
foo = data.foo;
baz = data.baz;

data = test2();
foo = data[0];
baz = data[1];
function foo(){
    return ["something","something else","something more","something further"];
}

let [a,b,c,d] = foo();

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