我试图在JavaScript 中返回两个值。这可能吗?
var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};
我试图在JavaScript 中返回两个值。这可能吗?
var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};
不,但您可以返回一个包含您的值的数组:
function getValues() {
    return [getFirstValue(), getSecondValue()];
}
然后你可以像这样访问它们:
var values = getValues();
var first = values[0];
var second = values[1];
借助最新的ECMAScript 6 语法*,还可以更直观地解构返回值:
const [first, second] = getValues();
如果您想在每个返回值上放置“标签”(更易于维护),您可以返回一个对象:
function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    };
}
并访问它们:
var values = getValues();
var first = values.first;
var second = values.second;
或者使用 ES6 语法:
const {first, second} = getValues();
* 有关浏览器兼容性,请参阅此表。基本上,除 IE 之外的所有现代浏览器都支持这种语法,但是您可以在构建时使用Babel 等工具将 ES6 代码编译为与 IE 兼容的 JavaScript 。
从 ECMAScript 6 开始,您可以使用数组和“解构赋值”来做到这一点。请注意,这些在较旧的 Javascript 版本中不可用(意思是 - ECMAScript 3rd 和 5th 版本都没有)。
它允许您同时分配 1+ 个变量:
var [x, y] = [1, 2];
x; // 1
y; // 2
// or
[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4
您还可以使用对象解构结合属性值速记来命名对象中的返回值并挑选出您想要的:
let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3
顺便说一句,不要被 ECMAScript 允许您return 1, 2, .... 那里真正发生的事情并不是看起来的那样。return 语句中的表达式 — 1, 2, 3— 只不过是一个逗号运算符,按顺序应用于数字文字 ( 1, 2, 和3),最终计算为其最后一个表达式 — 的值3。这就是为什么return 1, 2, 3在功能上与return 3.
return 1, 2, 3;
// becomes
return 2, 3;
// becomes
return 3;
只返回一个对象字面量
function newCodes(){
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return {
        dCodes: dCodes, 
        dCodes2: dCodes2
    };  
}
var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
从 ES6 开始,你可以这样做
let newCodes = function() {  
    const dCodes = fg.codecsCodes.rs
    const dCodes2 = fg.codecsCodes2.rs
    return {dCodes, dCodes2}
};
let {dCodes, dCodes2} = newCodes()
返回表达式{dCodes, dCodes2}是属性值的简写,相当于 this {dCodes: dCodes, dCodes2: dCodes2}。
最后一行的赋值称为对象破坏赋值。它提取对象的属性值并将其分配给同名变量。如果您想将返回值分配给不同名称的变量,您可以这样做let {dCodes: x, dCodes2: y} = newCodes()
Ecmascript 6 包括“解构赋值”(如 kangax 提到的),因此在所有浏览器(不仅仅是 Firefox)中,您将能够捕获一组值,而不必为了捕获它们而创建命名数组或对象。
//so to capture from this function
function myfunction()
{
 var n=0;var s=1;var w=2;var e=3;
 return [n,s,w,e];
}
//instead of having to make a named array or object like this
var IexistJusttoCapture = new Array();
IexistJusttoCapture = myfunction();
north=IexistJusttoCapture[0];
south=IexistJusttoCapture[1];
west=IexistJusttoCapture[2];
east=IexistJusttoCapture[3];
//you'll be able to just do this
[north, south, west, east] = myfunction(); 
您已经可以在 Firefox 中试用了!