JavaScript-ի find() մեթոդը
Մանրամասներ , օրինակներ, պրակտիկա
Երբ պետք է զանգվածից գտնես առաջին արժեքը, որը բավարարում է որոշակի պայման, ապա լավագույն ընտրությունը find() մեթոդն է։
Այն վերադարձնում է առաջին տարրը, որը բավարարում է քո սահմանած callback ֆունկցիային։ Եթե ոչ մի բան չի համընկնում՝ վերադարձնում է undefined։
array.find(function(element, index, array) { // վերադարձնում է true/false });
Պարամետրեր
const users = [ { id: 1, name: 'Anna' }, { id: 2, name: 'David' }, { id: 3, name: 'Levon' } ]; const foundUser = users.find(user => user.id === 2); console.log(foundUser); // { id: 2, name: 'David' }
Վերադարձնում է առաջին օգտատիրոջը, ում id-ն հավասար է 2։
Օրինակ
const result = users.find(user => user.id === 5); console.log(result); // undefined
const even = [1, 2, 3, 4, 5].find(n => n % 2 === 0); // 2 const evenList = [1, 2, 3, 4, 5].filter(n => n % 2 === 0); // [2, 4]
Երբ կանչում ենք՝
[1, 2, 3].find(fn);
Սա նույնն է ինչ՝
Array.prototype.find.call([1, 2, 3], fn);
function myFind(array, callback) { for (let i = 0; i < array.length; i++) { if (callback(array[i], i, array)) { return array[i]; } } return undefined; }
Օգտագործման օրինակ՝
const items = [10, 20, 30, 40]; const found = myFind(items, function(item) { return item > 25; }); console.log(found); // 30
Array.prototype.myFind = function(callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { return this[i]; } } return undefined; };
Օգտագործում ենք՝
const numbers = [5, 10, 15, 20]; const found = numbers.myFind(n => n > 10); console.log(found); // 15