วิธี findIndex() ของ JavaScript ใช้เพื่อส่งคืนดัชนีขององค์ประกอบแรกในอาร์เรย์ หากผ่านเงื่อนไข
ไวยากรณ์มีดังนี้ −
array.findIndex(function(currentValue, index, arr), thisValue)
ให้เราใช้วิธี findIndex() ใน JavaScript -
ตัวอย่าง
<!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>
ผลลัพธ์

คลิก “ผลลัพธ์” เพื่อรับดัชนี -

ตัวอย่าง
<!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>
ผลลัพธ์

ด้านบน ให้คลิกปุ่ม “ผลลัพธ์” −
