简体   繁体   English

如何从 JavaScript 函数中获取特定值?

[英]How to get a specific value out of a JavaScript function?

I have a simple code which returns the highest number value from an array.我有一个简单的代码,它从数组中返回最高数值。

const getMax = (data) => Object.entries(data).reduce((max, item) => max[1] > item[1] ? max : item);

var myData1 = { a: 1, b:2, c: 3};
var myData2 = { a: 4, b:2, c: 3};

console.log(getMax(myData1));
console.log(getMax(myData2));

Return result:返回结果:

[ 'c', 3 ]
[ 'a', 4 ]

This whole function is important to run for other purposes, but please how would I specifically print the output of only first calculated value (so 'c' or 'a') and then print specifically output of the second value (so 3 or 4)?整个函数对于其他目的运行很重要,但是请我如何专门打印仅第一个计算值的输出(例如“c”或“a”),然后专门打印第二个值的输出(例如 3 或 4) ?

Thank you.谢谢你。

A function can only return one value, whether simple or complex.一个函数只能返回一个值,无论是简单的还是复杂的。 You can store the complex value that a function returns, then use its individual simpler pieces:您可以存储函数返回的复杂值,然后使用其各个更简单的部分:

 const getMax = (data) => Object.entries(data).reduce((max, item) => max[1] > item[1] ? max : item); var myData1 = { a: 1, b:2, c: 3}; var myData2 = { a: 4, b:2, c: 3}; var result1 = getMax(myData1); var result2 = getMax(myData1); var simple1_0 = result1[0]; var simple1_1 = result1[1]; var simple2_0 = result2[0]; var simple2_1 = result2[1]; console.log(simple1_0); console.log(simple1_1); console.log(simple2_0); console.log(simple2_1);

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

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