JavaScript Array find()

Ορισμός και χρήση

find() Η μέθοδος επιστρέφει την τιμή του πρώτου στοιχείου που περνά τον έλεγχο (ως συνάρτηση που παρέχεται)

find() Η μέθοδος εκτελεί τη συνάρτηση σε κάθε στοιχείο του πίνακα που υπάρχει:

  • Αν βρεθεί στοιχείο του πίνακα που επιστρέφει true από τη συνάρτηση, η find() επιστρέφει την τιμή αυτού του στοιχείου (χωρίς να ελέγξει τα υπόλοιπα στοιχεία)
  • Εάν δεν βρεθεί τίποτα, επιστρέφει undefined

Note:find() Δεν εκτελεί τη συνάρτηση σε κενό πίνακα.

Note:find() Δεν αλλάζει τον αρχικό πίνακα.

Παράδειγμα

Παράδειγμα 1

Αποτελείται από το πρώτο στοιχείο του πίνακα που είναι 18 ή μεγαλύτερο;

var ages = [3, 10, 18, 20];
function checkAdult(age) {
  return age >= 18;
}
function myFunction() {
  document.getElementById("demo").innerHTML = ages.find(checkAdult);
}

Try it yourself

Example 2

Get the value of the first element in the array whose value is greater than a specific number:

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>Any ages above: <span id="demo"></span></p>
<script>
var ages = [4, 12, 16, 20];
function checkAdult(age) {
  return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
  document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
</script>

Try it yourself

Syntax

array.find(function(currentValue, index, arr) thisValue)

Parameter value

Parameter Description
function(currentValue, index, arr) Required. A function to be run for each element in the array.

Function parameters:

Parameter Description
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs.
thisValue

Optional. The value to be passed to the function as its "this" value.

If this parameter is empty, the value "undefined" will be passed as its "this" value.

Technical details

Return value: If any element in the array passes the test, return the element value, otherwise return undefined.
JavaScript version: ECMAScript 6

Browser support

The numbers in the table indicate the first browser version that fully supports this method.

Chrome Edge Firefox Safari Opera
Chrome 45 Edge 12 Firefox 25 Safari 7.1 Opera 32
September 2015 July 2015 July 2014 September 2014 September 2015

Note:Internet Explorer does not support find() Μέθοδος.

Σχετικές Σελίδες

Εκμάθηση:Αρχείο JavaScript

Εκμάθηση:Σταθερή Σειρά Αρχείου JavaScript

Εκμάθηση:Μέθοδοι Αρχείου JavaScript

Εκμάθηση:Σειρά Αρχείου JavaScript

Εκμάθηση:Εκτέλεση Σειράς Συνδυασμού JavaScript