Return multiple values in JavaScript?
I am trying to return two values in JavaScript. Is that 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:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return [dCodes, dCodes2];
};
Then you can access them like so:
var codes = newCodes();
var dCodes = codes[0];
var dCodes2 = codes[1];
If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return {
dCodes: dCodes,
dCodes2: dCodes2
};
};
And to access them:
var codes = newCodes();
var dCodes = codes.dCodes;
var dCodes2 = codes.dCodes2;
You can do this from Javascript 1.7 onwards using "destructuring assignments". Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).
It allows you to assign to 1+ variables simultaneously:
var [x, y] = [1, 2];
x; // 1
y; // 2
// or
[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4
You can also use object destructuring combined with property value shorthand to name the return values in an object and pick out the ones you want:
let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3
And by the way, don't be fooled by the fact that ECMAScript allows you to return 1, 2, ...
. What really happens there is not what might seem. An expression in return statement — 1, 2, 3
— is nothing but a comma operator applied to numeric literals ( 1
, 2
, and 3
) sequentially, which eventually evaluates to the value of its last expression — 3
. That's why return 1, 2, 3
is functionally identical to nothing more but 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);
链接地址: http://www.djcxy.com/p/63114.html
上一篇: Safari 5.1.4 showModalDialog返回undefined
下一篇: 在JavaScript中返回多个值?