Home Web Front-end JS Tutorial JS array learning returns the first element that meets the given conditions

JS array learning returns the first element that meets the given conditions

Aug 30, 2021 pm 05:14 PM
find() js array

In the previous article "JS Array Learning: Returning All Elements That Meet Given Conditions", we introduced the method of filtering array elements to obtain all elements that meet given conditions. This time we continue to talk about filtering elements and introduce the method of obtaining the first element that meets the given conditions. Friends in need can learn about it~

The main content of today’s article is: traversing arrays and detecting arrays Whether the elements in the array satisfy the specified condition, return the first array element that satisfies the condition. To put it simply: it filters the array elements according to the specified condition and returns the value of the first array element of the symbolic condition.

Let’s introduce 3 methods, starting with the familiar for loop, and then introducing 2 built-in functions-see how these two functions can filter array elements and obtain the first element that meets the conditions .

Method 1: Use for loop

Implementation idea: use for statement to traverse the array, and determine whether the array elements match in each loop Condition; when the first element meets the condition, it will be output immediately, and then use the break statement to exit the entire loop.

Let’s learn more about it through examples:

Example 1: Output the first element in the array whose age is greater than or equal to 18

var ages = [3, 10, 18, 20];
for(var i=0;i<ages.length;i++){
	if (ages[i] >= 18) {
		console.log(ages[i]);
		break;
	}
}
Copy after login

ages array There are two elements that are greater than or equal to 18, 18 and 20, but 18 is before 20, so the first element added is 18. Therefore the output result is:

JS array learning returns the first element that meets the given conditions

Example 2: Output the first non-numeric element in the array

var a = [1,"php中文网", 10, "red", 20,"22"];
for(var i=0;i<a.length;i++){
	var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字  //判断正整数/[1−9]+[0−9]∗]∗/ 
  if (!re.test(a[i])) { 
    console.log(a[i]);
		break;
  } 
}
Copy after login

Output result:

JS array learning returns the first element that meets the given conditions

Method 2: Use the find() method

find() method is in the array The function is called once for each element, and the given filter element is added within the callback function, and the first element that passes the test is returned.

  • When an element in the array returns true when testing the condition, find() returns the element that meets the condition, and the execution function will not be called for subsequent values.

  • If there is no element that meets the conditions, return undefined

Syntax:

array.find(function callbackfn(Value,index,array),thisValue)
Copy after login

function callbackfn(Value,index ,array): A callback function, which cannot be omitted, and can accept up to three parameters:

  • value: The value of the current array element, which cannot be omitted.

  • index: The numeric index of the current array element.

  • array: The array object to which the current element belongs.

Return value: Returns the first array element value that meets the test conditions. If there is no one that meets the conditions, undefined is returned.

Let’s learn more about it through examples:

Example 1: Output the first element in the array whose age is greater than or equal to 18

function checkAdult(age) {
    return age >= 18;
}
var ages = [3, 10, 18, 20];
var age=ages.find(checkAdult);
console.log(age);
Copy after login

Output results :

18
Copy after login

Example 2: Output the first non-numeric element in the array

function checkAdult(num) {
	var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字  //判断正整数/[1−9]+[0−9]∗]∗/ 
    return !re.test(num);
}

var a = [1,"php中文网", 10, "red", 20,"22"];
console.log(a.find(checkAdult));
Copy after login

Output result:

JS array learning returns the first element that meets the given conditions

Method 3: Use the findIndex() method

The findIndex() method calls the function once for each element in the array, and uses the Definitely add a filter element and return the index position of the first element that passes the test.

  • When an element in the array returns true when testing a condition, findIndex() returns the index position of the element that meets the condition, and subsequent values ​​will not call the execution function.

  • If there is no element that meets the conditions, return -1

Syntax:

array.findIndex(function callbackfn(Value,index,array),thisValue)
Copy after login

The syntax of this method and find() Similarly, parameter values ​​can be passed to the find() method.

Let’s learn more about it through examples:

Example 1: Output the first element in the array whose age is greater than or equal to 18

function checkAdult(age) {
    return age >= 18;
}
var ages = [3, 10, 18, 20];
var age=ages.findIndex(checkAdult);
console.log(age);
console.log(ages[age]);
Copy after login

findIndex( ) method can return the index of the first element that meets the condition. According to this index, the element value can be obtained using the form of "array name[index]". Therefore, the output result is:

JS array learning returns the first element that meets the given conditions

Example 2: Output the first non-numeric element in the array

function checkAdult(num) {
	var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字  //判断正整数/[1−9]+[0−9]∗]∗/ 
    return !re.test(num);
}

var a = [1,"php中文网", 10, "red", 20,"22"];
var index=a.findIndex(checkAdult);
console.log(index);
console.log(a[index]);
Copy after login

The output result is:

JS array learning returns the first element that meets the given conditions

Okay, that’s all. If you need it, you can watch it: javascript video tutorial

The above is the detailed content of JS array learning returns the first element that meets the given conditions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove elements from es6 array How to remove elements from es6 array Jan 11, 2023 pm 03:51 PM

Method: 1. Use shift() to delete the first element, the syntax is "array.shift()"; 2. Use pop() to delete the last element, the syntax is "array.pop()"; 3. Use splice() to delete Elements at any position, the syntax is "array.splice(position, number)"; 4. Use length to delete the last N elements, the syntax is "array.length=original array length-N"; 5. Directly assign the empty array "[ ]" to clear the element; 6. Use delete to delete an element at the specified subscript.

Can js array be converted into php array? Can js array be converted into php array? Jun 02, 2023 am 10:06 AM

The js array can be converted into a php array. The operation method is: 1. Create a php sample file; 2. Use the syntax "JSON.stringify()" to convert the js array into a string in JSON format; 3. Use the syntax "json_decode()" "Convert the JSON format string to a PHP array. The parameter true is added here, which means that the JSON format string is converted into a PHP associative array.

How to convert string to array in javascript How to convert string to array in javascript Nov 23, 2022 pm 07:28 PM

3 conversion methods: 1. Use split() to split a given string into a string array, the syntax is "str.split (separator, maximum length of array)"; 2. Use the expansion operator "... ", iterable string object, convert it into a character array, the syntax "[...str]"; 3. Use Array.from() to convert the string into an array, the syntax "Array.from(str) ".

How to get the length of an array in js How to get the length of an array in js Jun 20, 2023 pm 05:33 PM

Getting the length of an array in JS is very simple. Each array has a length property, which returns the maximum length of the array, that is, its value is equal to the maximum subscript value plus 1. Since numeric subscripts must be less than 2^32-1, the maximum value of the length attribute is equal to 2^32-1. The following code defines an empty array, and then assigns a value to the element with the index equal to 100, then the length property returns 101. Therefore, the length attribute cannot reflect the actual number of array elements.

How to use Python's find() function to find a substring in a string How to use Python's find() function to find a substring in a string Nov 18, 2023 am 09:16 AM

How to use Python's find() function to find substrings in a string. In Python's string processing, it is often necessary to find substrings in a string. Python provides the find() function to help us achieve this function. This article will introduce how to use Python's find() function to find substrings in a string, and give specific code examples. The find() function is a built-in method of the Python string object, which is used to find the position of a substring in a string. The letter

There are several ways to delete an element from a js array There are several ways to delete an element from a js array Aug 02, 2023 am 10:09 AM

There are 4 ways to delete an element from a js array, namely: 1. Use splice; 2. Use filter; 3. Use the pop method and shift; 4. Use the delete keyword.

JS array sorting: how to use the sort() method JS array sorting: how to use the sort() method Dec 27, 2023 pm 03:40 PM

JavaScript's Array.prototype.sort() method is used to sort the elements of an array. This method sorts in place, that is, it modifies the original array rather than returning a new sorted array. By default, the sort() method sorts strings according to their Unicode code point values. This means that it is used primarily for sorting strings and numbers, rather than for sorting objects or other complex data types.

What are the methods to remove duplicates from js arrays? What are the methods to remove duplicates from js arrays? Aug 09, 2023 pm 04:47 PM

Methods to deduplicate js arrays include using Set, using indexOf, using includes, using filter and using reduce. 1. Use Set, which is characterized by the fact that the elements in the set will not be repeated; 2. Use indexOf to return the first index position of the specified element in the array; 3. Use includes to determine whether an element already exists in the array. 4. Use filter to filter elements; 5. Use reduce to compress elements in an array, etc.

See all articles