Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中返回多个值?(Return multiple values in JavaScript?)

I am trying to return two values in JavaScript.(我试图在JavaScript中返回两个值。)

Is that possible?(那可能吗?)
var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};
  ask by Autolycus translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, but you could return an array containing your values:(不,但是您可以返回一个包含您的值的数组:)

function getValues() {
    return [getFirstValue(), getSecondValue()];
}

Then you can access them like so:(然后,您可以像这样访问它们:)

var values = getValues();
var first = values[0];
var second = values[1];

With the latest ECMAScript 6 syntax *, you can also destructure the return value more intuitively:(使用最新的ECMAScript 6语法 *,您还可以更直观地分解返回值:)

const [first, second] = getValues();

If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:(如果要将“标签”放在每个返回值上(便于维护),则可以返回一个对象:)

function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    };
}

And to access them:(并访问它们:)

var values = getValues();
var first = values.first;
var second = values.second;

Or with ES6 syntax:(或使用ES6语法:)

const {first, second} = getValues();

* See this table for browser compatibility.(*有关浏览器兼容性,请参见下表)

Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like Babel .(基本上,除IE之外,所有现代浏览器都支持此语法,但是您可以在构建时使用Babel之类的工具将ES6代码编译为IE兼容的JavaScript。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...