我需要撰寫一些函式,這些函式涉及與 Sheets 函式 MATCH() 相同的函式,引數“排序型別”設定為 TRUE 或 1,以便在 [10,20,30,40] 中搜索 35 將產生 2,指數為 30,次低值為 35。
我知道我可以通過遍歷陣列進行搜索來做到這一點,并根據我的搜索值測驗每個值,直到找到一個大于搜索值的值,但在我看來,必須有一種速記方法可以做到這一點。在尋求精確值時,我們不必這樣做;我們可以只使用 indexOf()。當我第一次了解到 indexOf() 沒有用于搜索型別的引數時,我感到很驚訝,但如果找不到確切的值,則只能回傳 -1。
是否沒有類似于 indexOf() 的函式可以執行此操作,還是每次需要執行此操作時實際上都需要遍歷陣列?
uj5u.com熱心網友回復:
可能你正在尋找array.find()方法。推動可能是這樣的:
var arr = [10,20,30,40]
// make a copy of the array, reverse it and do find with condition
var value = arr.slice().reverse().find(x => x < 35)
console.log(value) // output --> 30 (first element less than 35 in the reversed array)
var index = arr.indexOf(value)
console.log(index) // output --> 2 (index of the element in the original array)
https://www.w3schools.com/jsref/jsref_find.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
還有另一種方法array.findIndex()。也許你也可以使用它:
var arr = [10,20,30,40]
// find more or equal 35 and return previous index
var index = arr.findIndex(x => x >= 35) - 1
console.log(index) // output --> 2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365569.html
下一篇:計算谷歌表格單元格上的出現次數
