[JavaScript Basic Grammar] Methods for the web front end to determine whether an array object contains a certain value (6 types)
knowledge callback
Article content | article link |
---|---|
Vue3 antd table addition, deletion, modification and query (1)The input input box is searched according to keywords [Background management system pure front-end filter filtering] | https://blog.csdn.net/XSL_HR/article/details/128072584?spm=1001.2014.3001.5501 |
Vue3 antd table addition, deletion, modification and query (2)The input input box is searched according to keywords [Background management system requests front-end and back-end interaction of back-end interface] | https://blog.csdn.net/XSL_HR/article/details/128089801?spm=1001.2014.3001.5501 |
Scene recurrence
In the project development of the background management system, the processing of array objects is very common, such asSorting of array objects、Filtering of Array ObjectsandFuzzy query for array objects. In the previous articles, we introduced the sorting and filtering of array objects. This article mainly introduces the method of judging whether an array object contains a certain value .
Implementation methods (6 types)
Loop through array elements
- Using loops to traverse array elements is a more traditional and older implementation, but it is undeniable that this methodIt is more efficient in the browser and understands it quickly。
- However, when there are many restrictive conditions, there will be problems of multi-layer loops and multiple data processing.
function contains(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return true;
}
}
return false;
}
contains([1,2,3],3);//true
Of course, you can also use while
the statement
function contains(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val){
return true;
}
}
return false;
}
contains([1,2,3,4],1);//true
Use some, filter method
Using the some method is more concise,The iteration terminates once the element is found, thereby avoiding unnecessary iteration cycles (but using loops can also be solved, but it increases the amount of code)
Sample code:
function contains(arr, val) {
return arr.some(item => item === val);
}
Here you can directly use the arrow function to filter the data, which is more concise than the loop.
It is most common to use the filter method. The filter itself means filtering.Generally, filter conditions are added to the arrow function of filter。
(Notice:array.filter(e=>e==x).length > 0
equivalent toarray.some(e=>e==x)
, but some more efficient)
Sample code:
function contains(arr, val) {
return arr.filter((item)=> {
return item == val }).length > 0;
}
Using the array.indexOf method
array.indexOf
this methodCheck if a value exists in an array,if it existsReturns the subscript of an array element, otherwise -1 is returned.- The indexOf method is very commonly used when filtering array data, and is generally used for fuzzy query and keyword search.
[1, 2, 3].indexOf(1);//0
["foo", "fly63", "baz"].indexOf("fly63");//1
[1, 2, 3].indexOf(4);//-1
Notice:
indexOf()
methodcase sensitive. If the string value to be retrieved is not present, the method returns -1.- When comparing the first argument with each item in the array, the identity operator is used, i.e.Items to be looked up must be strictly equal。
- The position of the array is added by ECMAScript5 for the array instance, and the supported browsers include IE9+, Firefox, Safari, Opera, and Chrome.
Using the array.includes method
array.includes(searchElement[, fromIndex])
this methodCheck if a value exists in an array- Returns true if present, false otherwise.
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
it also acceptsOptional second parameter fromIndex:
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
Unlike indexOf, it uses strict equality comparison. this means youIt is possible to detect whether an array contains NaN:
[1, 2, NaN].includes(NaN); // true
Also different from indexOf,includes does not skip missing indexes:
new Array(5).includes(undefined); // true
Using the array.find method
find is used to return the arraythe value of the first element that satisfies the condition, if not, return undefined
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => {
return item > 8;
});
console.log(result);//12
//元素是对象
let items = [
{
id: 1, name: 'something'},
{
id: 2, name: 'anything'},
{
id: 3, name: 'nothing'},
];
let item = items.find(item => {
return item.id == 3;
});
console.log(item) //Object { id: 3, name: "nothing" }
Except find
, we can also use array.indIndex
. Returns the index (subscript) of the first element in the array that satisfies the condition, if not found, returns -1 (similar to the third method indexOf
)
Use the has method in set
function contains(arr, val) {
return new Set(arr).has(val)
}
contains([1,2,3],2);//true
By new set([])
converting the array into a Set object, set.prototype.has(value)
determine whether the value exists in the Set object, returnBoolean value。
Extension : In addition, it can also be used forArray deduplication
let arr2 = new Set([1,1,2,3,4])
let arr3 = [...arr2]
console.log(arr2,arr3) // {1,2,3,4} [1,2,3,4]
Summary of this issue
This article detailssix ways, forDetermine whether an array object contains a certain value. Of course, in previous articles, we used filter and indexOf to perform simple additions, deletions, modifications, and queries on the data, but whenThe queried data becomes the array object in the array object, how should we solve it?