JavaScript 陣列 findIndex() 函式
JavaScript 的 findIndex() 方法用於在滿足條件的情況下返回陣列中第一個元素的索引。
語法如下 −
array.findIndex(function(currentValue, index, arr), thisValue)
下面我們來實現 JavaScript 中的 findIndex() 方法 −
示例
<!DOCTYPE html>
<html>
<body>
<h2>Rank</h2>
<button onclick="display()">Result</button>
<p id="demo"></p>
<p>Finding the index of the player with highest rank.</p>
<script>
var points = [100, 150, 200, 250, 300, 400];
function topRank(points) {
return points >= 400;
}
function display() {
document.getElementById("demo").innerHTML = "index = "+points.findIndex(topRank);
}
</script>
</body>
輸出

點選“Result”以獲取索引 −

示例
<!DOCTYPE html>
<html>
<body>
<h2>Rank</h2>
<button onclick="display()">Result</button>
<p id="demo"></p>
<p>Finding the index of the player with specific rank points.</p>
<script>
var points = [100, 150, 200, 250, 300, 400];
function topRank(points) {
return points == 200;
}
function display() {
document.getElementById("demo").innerHTML = "index = "+points.findIndex(topRank);
}
</script>
</body>
輸出

上方,點選“Result”按鈕 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP