我试图在 JavaScript 中返回两个值.这可能吗?
I am trying to return two values in JavaScript. Is this possible?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
不,但你可以返回一个包含你的值的数组:
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];
使用最新的 ECMAScript 6 语法*,也可以更直观的解构返回值:
With the latest ECMAScript 6 syntax*, you can also destructure the return value more intuitively:
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(),
};
}
并访问它们:
var values = getValues();
var first = values.first;
var second = values.second;
或者使用 ES6 语法:
Or with ES6 syntax:
const {first, second} = getValues();
* 请参阅此表了解浏览器兼容性.基本上,除了 IE 之外的所有现代浏览器都支持这种语法,但是您可以在构建时使用 之类的工具将 ES6 代码编译为与 IE 兼容的 JavaScript通天塔.
* 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.
这篇关于在 JavaScript 中返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!