![](/img/trans.png)
[英]Compare a string value to an array and if it matches get the index of the array item
[英]How to compare a value in array to get the right index?
大家好,我有點卡在邏輯 function 中,我有一個時間為 position 的數組。 我想檢查當前 position 是否介於兩個 position 值之間,然后返回當前 position 的索引。
所以數組看起來像這樣;
const PLAYLIST = [{"position":"01:35"}, {"position":"05:44"}, {"position":"09:14"}, {"position":"12:00"}]
現在當前07:22
是 07:22 所以它適合{"position":"05:44"}
和{"position":"09:14"}
所以它應該返回索引 1
var arr = [{
"position": "01:35"
}, {
"position": "05:44"
}, {
"position": "09:14"
}, {
"position": "12:00"
}]
var currentPosition = "09:22";
var closestSmallIndex = fetchClosestIndex(currentPosition);
console.log(closestSmallIndex)
function fetchClosestIndex(currentPosition) {
for (var i = 0; i < arr.length; i++) {
var position = arr[i].position;
if (position > currentPosition) {
return i - 1;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.