简体   繁体   English

从 JavaScript 函数返回多个值

[英]Returning multiple values from a JavaScript function

I'm a newcomer to JavaScript and I'm sure this is very straightforward: I wish to set a number of values based upon a single input in a switch statement.我是 JavaScript 的新手,我确信这非常简单:我希望根据 switch 语句中的单个输入设置多个值。 I know in Java I would use getters/setters and or pass the values into an array and pick the relevant field based on its index.我知道在 Java 中我会使用 getter/setter 和/或将值传递到数组中并根据其索引选择相关字段。

 let custCode; let loyaltyCode; let id; const setCustomerCodes = () => { switch (customerType) { case "NEW": (custCode = "19202"), (loyaltyCode = "X78"), (id = "396550"); break; case "CURRENT": (custCode = "93893"), (loyaltyCode = "X89"), (id = "396438"); break; case "LOYAL": (custCode = "76353"), (loyaltyCode = "X90"), (id = "396440"); break; default: (custCode = "02902"), (loyaltyCode = "X80"), (id = "396637"); break; } return //all values as an object?; }; module.exports = { //export the values to use in separate file };

I then just want to use the value of each field in a separate JS file.然后我只想在单独的 JS 文件中使用每个字段的值。 I know this is very basic;我知道这是非常基本的; easier when I can get my head around debugging in VS Code当我可以在 VS Code 中进行调试时更容易

Here is one possible solution:这是一种可能的解决方案:

 let custCode; let loyaltyCode; let id; const setCustomerCodes = (customerType) => { switch (customerType) { case "NEW": (custCode = "19202"), (loyaltyCode = "X78"), (id = "396550"); break; case "CURRENT": (custCode = "93893"), (loyaltyCode = "X89"), (id = "396438"); break; case "LOYAL": (custCode = "76353"), (loyaltyCode = "X90"), (id = "396440"); break; default: (custCode = "02902"), (loyaltyCode = "X80"), (id = "396637"); break; } return {custCode, loyaltyCode, id} }; let x = setCustomerCodes("NEW"); console.log(x); console.log(x.custCode); console.log(x.loyaltyCode); console.log(x.id);

As @VLAZ suggests, you simply return all of the values in {} as a single object.正如@VLAZ 所建议的,您只需将 {} 中的所有值作为单个对象返回。 The x variable I have defined can then be used to get to the individual values (as shown in the separate console.log(...) entries.然后,我定义的x变量可用于获取各个值(如单独的console.log(...)条目中所示。

Note that you do need to pass in a value for customerType , so I've included that as a parameter请注意,您确实需要为customerType传入一个值,因此我将其作为参数包含在内

I think you could return an object.我认为你可以返回一个对象。

 const setCustomerCodes = () => { switch (customerType) { case "NEW": return {custCode: "19202", loyaltyCode: "X78", id: "396550"} case "CURRENT": return {custCode: "93893", loyaltyCode: "X89", id: "396438"}; case "LOYAL": return {custCode: "76353", loyaltyCode: "X90", id: "396440"}; default: return {custCode: "02902", loyaltyCode: "X80", id: "396637"}; } }; const { custCode, loyaltyCode, id, } = setCustomerCodes() module.exports = { custCode, loyaltyCode, id, };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM