qwe*_*ret 4 javascript arrays sorting variables return
所以我使用JavaScript,并且有一个变量数组。
var a=5,b=10,c=3,d=11,e=0; //5 Variables with randomly chosen values
var myArray=[a,b,c,d,e];
myArray.sort(); //sort them, so the lowest value or variable is on first place
alert("This Variable has the lowest value: " + myArray[0]);
//tell me the variable with the lowest value
Run Code Online (Sandbox Code Playgroud)
因此,基本上,我将得到以下文本:“此变量的最低值为:0”
但是我想要的是:“此变量的值最低:e”
我如何返回变量,而不是变量的值?
最好的问候qweret
您需要制作一个对象数组:
var array = [{key: 'a', value: 5}, {key: 'b', value: 10}, {key: 'c', value: 3}, {key: 'd', value: 10}, {key: 'e', value: 0}];
Run Code Online (Sandbox Code Playgroud)
然后应用一个sort函数:
array.sort(function(obj1, obj2) {
return obj1.value - obj2.value;
});
Run Code Online (Sandbox Code Playgroud)
显示警报:
alert("This Variable has the lowest value: " + array[0].key);
Run Code Online (Sandbox Code Playgroud)
看到它在这里行动。