JavaScript 陣列 find() 函式
JavaScript 的 find() 方法用於返回陣列中的第一個元素值(如果條件透過的話),否則返回值是未定義的。語法如下所示 -
array.find(function(val, index, arr),thisValue)
其中,function 是一個與 val(當前元素值)相關的函式。index 是陣列索引,arr 是陣列。this 值引數是傳遞給函式的值。
示例
<!DOCTYPE html>
<html>
<body>
<h2>Ranking Points</h2>
<p>Get the points (first element) above 400...</p>
<button onclick="display()">Result</button>
<p id="demo"></p>
<script>
var pointsArr = [50, 100, 200, 300, 400, 500, 600];
function pointsFunc(points) {
return points > 400;
}
function display() {
document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
}
</script>
</body>
</html>輸出

現在,點選 “結果” 按鈕 -

我們再看另一個示例,其中的結果將是未定義的 -
示例
<!DOCTYPE html>
<html>
<body>
<h2>Ranking Points</h2>
<p>Get the points (first element) above 400...</p>
<button onclick="display()">Result</button>
<p id="demo"></p>
<script>
var pointsArr = [50, 100, 200, 300, 400];
function pointsFunc(points) {
return points > 400;
}
function display() {
document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc);
}
</script>
</body>
</html>輸出
現在,點選 “結果” 按鈕 -

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