当前位置:网站首页>JS five methods to judge whether a certain value exists in an array

JS five methods to judge whether a certain value exists in an array

2022-06-23 20:33:00 It workers

1.javascript Of indexOf() Method

var arr_data = [1,2,3];

arr_data.indexOf(1); // If there is a subscript for the return value , There is no return -1

2.jquery Of $.inArray() Method

$.inArray(1, arr_data); // If there is a subscript for the return value , There is no return -1

3.arr.find()

Of the array instance find() Used to find the first array element that matches the condition . Its argument is a callback function , All array elements traverse the callback function in turn , Until you find out that the first return value is true The elements of , Then return the element , Otherwise return to undefined.

Be careful :find() For an empty array , Functions do not execute .find() It doesn't change the original value of the array

arr.find(function(value) { 

 if(value ===  Value to find ) { 

 // Contains the element  

}})

4.arr.findIndex() Returns the position of the first eligible array element , If all the elements do not meet the conditions , Then return to -1.

Be careful :find(),findIndex() Make up for index Deficiency :( Judgment NAN)

[NaN].indexOf(NaN) // -1

[NaN].findIndex(y => Object.is(NaN, y))// 0

5.for Circulation and if Judge

var arr = [1, 5, 10, 15];
// Tradition for
for(let i=0; i<arr.length; i++) {
    if(arr[i] ===  Find value ) {
        // Contains the element 
    }
}
// for...of
for(v of arr) {
    if(v ===  Find value ) {
        // Contains the element 
    }
}
//forEach
arr.forEach(v=>{
    if(v ===  Find value ) {
        // Contains the element 
    }
})
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112302251509366.html