[英]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.