[英]Finding the min index in the array javascript
var myArray = [];
let maxNum = 15;
function findMin(A, start, end){
var result = Math.min.apply(null, myArray)
console.log(result)
return 0;
}
这个 function 应该找到数组 A 中最小值的索引,查看从索引开始到索引结束的所有值。 这包括开始和结束的数字。
返回出现最小值的 INDEX。
例如,如果 A = [3,2,1,6,4] findMax(A, 0,4) 应该返回 2,因为最小值为 1,并且它出现在此数组中的 position 2 处。
我将如何找到最小数字的索引?
(myArray 已经随机生成数组中的数字,我只是不知道如何找到数组中最小数字的索引)
您可以使用最小值的indexOf()
。 或者您使用forEach
手动遍历数组并记住最小值和它的索引。
数组原型indexOf返回数组中值的第一个索引。 首先,您需要找到起始索引和结束索引之间的最小值。 这就是我们使用返回子数组的slice的原因。
数组slice
的示例。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(1, 3));
// slice will return the items from index 1 to upto 3
// expected output: Array ["bison", "camel"]
然后我们要做的就是找到最小值并返回indexOf
。
function findMin(A, start, end){
let minValue = Math.min.apply(A.slice(start, end))
return A.indexOf(Math.min.apply(Math, A));
}
let A = [3,2,1,6,4]
console.log( findMin( A, 0, 4) )
我们也可以使用 ES6 箭头 function 来表达相同的 function。
const findMin = (A, start, end) => A.indexOf(Math.min.apply(Math, A))
let A = [3,2,1,6,4]
console.log( findMin( A, 0, 4) )
试试这个方法。
let myArray = [5,3,4,1,9];
let maxNum = 15;
function findMin(A, start, end){
let result = Math.min.apply(null, myArray)
console.log(myArray.indexOf(result))
}
findMin(myArray, 0, myArray.length)
您可以结合使用 Math.min 和扩展语法
const arr = [3,2,1,6,4]
const index = arr.indexOf(Math.min(...arr))
console.log(index) // 2
这是你要找的东西吗
var ary = [1,6,8,2,0,8,9]
function findMin(A, start, end) {
var finalAry = A.slice(start, end);
var result = Math.min.apply(null, finalAry)
return A.indexOf(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.