Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the functions judged by functional array logic?

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the functions of functional array logic judgment". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow Xiaobian's train of thought to study and learn what are the functions of functional array logic judgment.

1.1 Overview of array.filter ()

The filter () method creates a new array that contains all the elements of the test implemented by the provided function.

Syntax var newArray = arr.filter (callback (element [, index [, array]]) [, thisArg]) parameter

The function that callback uses to test each element of the array. Returning true means that the element passes the test, keeping the element and not false. It accepts the following three parameters:

-the element currently being processed in the element array.

-index selects the index of the element being processed in the array.

-array optionally calls the array itself of filter.

ThisArg optional value for this when callback is executed.

Return value

A new array of elements that pass the test, and returns an empty array if none of the array elements pass the test.

1.2 array.filter () description

Filter calls the callback function once for each element in the array and creates a new array with all the elements that make callback return true or the equivalent of true. Callback will only be called on indexes that have been assigned, not those that have been deleted or have never been assigned. Elements that fail the callback test are skipped and are not included in the new array.

Three parameters are passed in when callback is called:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

The value of the element

Index of the element

The array itself that is traversed

If you provide a thisArg parameter for filter, it will be used as the this value when callback is called. Otherwise, the this value of callback will be a global object in non-strict mode and undefined in strict mode. The final this value observed by the callback function is determined based on the rules of "this" that the function usually sees.

Filter does not change the original array, it returns the filtered new array.

The range of elements for filter traversal is determined before the first call to callback. Elements that are added to the array after calling filter are not traversed by filter. If elements that already exist are changed, the value they pass in callback is the value that filter traverses to their moment. Elements that have been deleted or never assigned will not be traversed.

Case 01 filtering excludes all smaller values

The following example uses filter to create a new array whose elements are made up of elements with values greater than 10 in the original array.

Function isBigEnough (element) {return element > = 10;} var filtered = [12,5,8,130,44] .filter (isBigEnough); / / filtered is [12,130,44] case 02 filters invalid entries in JSON

The following example uses filter () to create a json with an element with non-zero id.

Var arr = [{id: 15}, {id:-1}, {id: 0}, {id: 3}, {id: 12.2}, {id: null}, {id: NaN}, {id: 'undefined'}]; var invalidEntries = 0; function isNumber (obj) {return obj! = = undefined & typeof (obj) = =' number' & &! isNaN (obj) } function filterByID (item) {if (isNumber (item.id) & & item.id! = 0) {return true;} invalidEntries++; return false;} var arrByID = arr.filter (filterByID); console.log ('Filtered Array\ n é, arrByID); / / Filtered Array / / [{id: 15}, {id:-1}, {id: 3}, {id: 12.2}] console.log (' Number of Invalid Entries =', invalidEntries) / / Number of Invalid Entries = 5 case 03 search in the array

The following example uses filter () to filter the contents of the array based on search criteria.

Var fruits = ['apple',' banana', 'grapes',' mango', 'orange']; / * * Array filters items based on search criteria (query) * / function filterItems (query) {return fruits.filter (function (el) {return el.toLowerCase (). IndexOf (query.toLowerCase ()) >-1;})} console.log (filterItems (' ap')) / / ['apple',' grapes'] console.log (filterItems ('an')); / / [' banana', 'mango',' orange'] case 04 ES2015 implements const fruits = ['apple',' banana', 'grapes',' mango', 'orange'] / * Array filters items based on search criteria (query) * / const filterItems = (query) = > {return fruits.filter ((el) = > el.toLowerCase (). IndexOf (query.toLowerCase ()) >-1);} console.log (filterItems ('ap')); / / [' apple', 'grapes'] console.log (filterItems (' an')); / / [banana', 'mango',' orang2.1 array.find () Overview

The find () method returns the value of the first element in the array that satisfies the provided test function. Otherwise, undefined is returned.

Const array1 = [5,12,8,130,44]; const found = array1.find (element = > element > 10); console.log (found); / / expected output: 12

See also the 3. 1 findIndex () method, which returns the index of the element found in the array instead of its value.

If you need to find the location of an element or whether an element exists in an array, use Array.prototype.indexOf () or Array.prototype.includes ().

Syntax arr.find (callback [, thisArg])

Parameters.

A function that callback executes on each item of the array, receiving three arguments:

The element that element is currently traversing.

Index can select the index to which it is currently traversed.

The array optional array itself.

ThisArg optionally serves as an object for this when performing a callback.

Return value

The value of the first element in the array that satisfies the provided test function, otherwise undefined is returned.

2.2 array.find () description

The find method executes the callback function on each element in the array once until a callback returns true. When such an element is found, the method immediately returns the value of the element, otherwise it returns undefined. Note that the callback function calls from 0 to length-1 for each index in the array, not just those assigned indexes, which means that for sparse arrays, this method is less efficient than those that only traverse indexes with values.

The callback function takes three parameters: the value of the current element, the index of the current element, and the array itself.

If the thisArg parameter is provided, it serves as the this for each execution of the callback function, and if it is not provided, undefined is used.

The find method does not change the array.

The index range of the element is determined the first time the callback function is called, so the new elements added to the array after the find method starts execution will not be accessed by the callback function. If the value of an element in the array that has not been accessed by the callback function is changed by the callback function, then when the callback function accesses it, its value will be the current value accessed based on its index in the array. The deleted element will still be accessed, but its value is already undefined.

Case 01 uses object attributes to find objects in the array var inventory = [{name: 'apples', quantity: 2}, {name:' bananas', quantity: 0}, {name: 'cherries', quantity: 5}]; function findCherries (fruit) {return fruit.name =' cherries';} console.log (inventory.find (findCherries)); / / {name: 'cherries', quantity: 5} case 02 finds prime numbers in the array

The following example shows how to find a prime number from an array (return undefined if no prime number is found)

Function isPrime (element, index, array) {var start = 2; while (start 1;} console.log ([4,6,8,12] .find (isPrime)); / / undefined, not found console.log ([4,5,8,12] .find (isPrime)); / / 5

When a value in the array is deleted in the callback, when this location is accessed, the value passed in is undefined:

/ / Declare array with no element at index 2,3 and 4 var a = [0Visited index 1, with value 6]; / / Shows all indexes, not just those that have been assigned values a.find (function (value, index) {console.log ('Visited index' + index + 'with value' + value);}) / / Shows all indexes, including deleted a.find (function (value, index) {/ / Delete element 5 on first iteration if (index = = 0) {console.log ('Deleting a [5] with value' + a [5]); delete a [5] / Note: just set a [5] to undefined. You can try a.pop () to delete the last item, and still traverse to the deleted entry} / / Element 5 is still visited even though deleted console.log ('Visited index' + index + 'with value' + value);}); 3.1 array.findIndex () Overview

The findIndex () method returns the index of the first element in the array that satisfies the provided test function. If the corresponding element is not found,-1 is returned.

Var inventory = [{name: 'apples', quantity: 2}, {name:' bananas', quantity: 0}, {name: 'cherries', quantity: 5}]; function findCherries (fruit) {return fruit.name =' cherries';} console.log (inventory.find (findCherries)); / {name: 'cherries', quantity: 5}

See also the 1.1 find () method, which returns the value of the element found in the array instead of its index.

Syntax arr.findIndex (callback [, thisArg]) parameter

Callback executes the callback function for each element in the array, and the following three parameters are passed in automatically:

-element the current element.

-index the index of the current element.

-array calls the array of findIndex.

ThisArg is optional. As the value of the this object when callback is executed.

Return value

Array by providing the index of the first element of the test function. Otherwise, return-1

3.2 array.findIndex () description

The findIndex method executes the callback function once on each array index 0..length-1 (including) in the array until a callback function returns a real value (forced to be true). If such an element is found, findIndex immediately returns the index of the element. If the callback never returns a true value, or if the length of the array is 0, findIndex returns-1. Unlike some other array methods, such as Array#some, in sparse arrays, callback functions are called even on the index of items that do not exist in the array.

The callback function is called with three parameters: the value of the element, the index of the element, and the array to be traversed.

If a thisArg parameter is provided to findIndex, it will be used as a this each time the callback function is called. If not provided, undefined will be used.

FindIndex does not modify the called array.

The index range of the element is determined the first time the callback function is called, so the new elements added to the array after the findIndex method starts execution will not be accessed by the callback function. If the value of an element in the array that has not been accessed by the callback function is changed by the callback function, then when the callback function accesses it, its value will be the current value accessed based on its index in the array. Deleted elements are still accessed.

Case 01 finds the index of the first prime element in the array

The following example finds the index of the element of a prime in an array (returns-1 if there is no prime).

Function isPrime (element, index, array) {var start = 2; while (start 1;} console.log ([4,6,8,12] .find (isPrime)); / / undefined, not found console.log ([4,5,8,12] .find (isPrime)); / / 54.1 array.includes () Overview

When the 2. 1 array.find looks for a specific element, it is array.include.

The includes () method is used to determine whether an array contains a specified value, returning true if it does, or false otherwise.

Syntax arr.includes (valueToFind [, fromIndex])

Parameters.

ValueToFind

The value of the element to look for.

Note: using includes () to compare strings and characters is case-sensitive.

FromIndex optionally starts looking for valueToFind at the fromIndex index. If it is negative, the search starts with the index of array.length + fromIndex in ascending order (even though the index of the absolute value of fromIndex is skipped forward from the end, and then searched backward). The default is 0.

Return value

Returns a Boolean value of Boolean, or true if found in the array (if fromIndex is passed in, it is found in the index range specified by fromIndex).

Case 00 simple examples [1, 2, 3] .examples (2); / / true [1, 2, 3] .examples (4); / / false [1, 2, 3] .examples (3, 3); / / false [1, 2, 3] .examples (3,-1); / / true [1, 2, NaN] .examples (NaN); / / true case 01 fromIndex greater than or equal to the array length

If fromIndex is greater than or equal to the length of the array, false is returned and the array is not searched.

Var arr = ['averse,' baked,'c']; arr.includes ('clocked, 3); / / false arr.includes (' clocked, 100); / / the index calculated by false case 02 is less than 0

If fromIndex is negative, the calculated index will be used as the location to start the search for searchElement. If the calculated index is less than 0, the entire array is searched.

/ / array length is 3 / / fromIndex is-100 / / computed index is 3 + =-97 var arr = ['averse,' baked,'c']; arr.includes ('axed,-100); / / true arr.includes (' baked,-100); / / true arr.includes ('cased,-100); / / true arr.includes (' averse,-2); / / false case 03 includes () as a general method

The includes () method is intentionally designed as a generic method. It does not require the th value to be an array object, so it can be used for other types of objects (such as class array objects). The following example shows the includes () method called on the function's arguments object.

(function () {console.log ([] .includes.call (arguments,'a')); / / true console.log ([] .includes.Call (arguments,'d')); / / false}) ('axiomagy'); 5.1 array.indexOf () Overview

The indexOf () method returns the first index where a given element can be found in the array, or-1 if it does not exist.

Syntax arr.indexOf (searchElement [, fromIndex]) parameter

SearchElement

The element to find

FromIndex optional

The location where you started looking. If the index value is greater than or equal to the length of the array, it means that it will not be looked up in the array and returns-1. If the index value provided in the parameter is a negative value, it is used as an offset at the end of the array, that is,-1 means to start with the last element,-2 means to start with the penultimate element, and so on. Note: if the index value provided in the parameter is a negative value, it does not change the search order, which is still the front-to-back query array. If the offset index value is still less than 0, the entire array will be queried. Its default value is 0.

Return value

The index position of the first found element in the array; if not found, returns-1

5.2 array.indexOf () description

IndexOf uses strict equality (both the = = and triple-equals operators are based on the same method) to determine the relationship between searchElement and the elements contained in the array.

Case 01 using indexOf

The following example uses the indexOf method to determine the position of multiple values in an array.

Var array = [2, 5, 9]; array.indexOf (2); / / 0 array.indexOf (7); / /-1 array.indexOf (9, 2); / / 2 array.indexOf (2,-1); / /-1 array.indexOf (2,-3); / / 0 case 02 find all locations where the specified element appears var indices = [] Var array = ['asides,' baked, 'asides,' canals, 'asides,' d']; var element = 'a'; var idx = array.indexOf (element); while (idx! =-1) {indices.push (idx); idx = array.indexOf (element, idx + 1);} console.log (indices) / / [0,2,4] case 03 determines whether an element is in the array or updates the array function updateVegetablesCollection (veggies, veggie) {if (veggies.indexOf (veggie) =-1) {veggies.push (veggie); console.log ('New veggies collection is:' + veggies);} else if (veggies.indexOf (veggie) >-1) {console.log (veggie + 'already exists in the veggies collection.') }} var veggies = ['potato',' tomato', 'chillies',' green-pepper']; / / New veggies collection is: potato,tomato,chillies,green-papper,spinach updateVegetablesCollection (veggies, 'spinach'); / / spinach already exists in the veggies collection. UpdateVegetablesCollection (veggies, 'spinach'); thank you for your reading, these are the contents of "what are the functions of functional array logic judgment". After the study of this article, I believe you have a deeper understanding of what the functions of functional array logic judgment have, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report