繁体   English   中英

从 JavaScript 函数返回多个值

[英]Returning multiple values from a JavaScript function

我是 JavaScript 的新手,我确信这非常简单:我希望根据 switch 语句中的单个输入设置多个值。 我知道在 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 };

然后我只想在单独的 JS 文件中使用每个字段的值。 我知道这是非常基本的; 当我可以在 VS Code 中进行调试时更容易

这是一种可能的解决方案:

 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);

正如@VLAZ 所建议的,您只需将 {} 中的所有值作为单个对象返回。 然后,我定义的x变量可用于获取各个值(如单独的console.log(...)条目中所示。

请注意,您确实需要为customerType传入一个值,因此我将其作为参数包含在内

我认为你可以返回一个对象。

 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