数组中最小的数字及其位置 [英] Smallest number in array and its position
本文介绍了数组中最小的数字及其位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要实现的目标是找到数组中最小的数字及其初始位置.这是一个示例,它应该做什么:
What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.
推荐答案
仅循环遍历数组并查找最低编号:
Just loop through the array and look for the lowest number:
var index = 0;
var value = temp[0];
for (var i = 1; i < temp.length; i++) {
if (temp[i] < value) {
value = temp[i];
index = i;
}
}
现在 value
包含最小值,而 index
包含在数组中存在此类值的最低索引.
Now value
contains the lowest value, and index
contains the lowest index where there is such a value in the array.
这篇关于数组中最小的数字及其位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文