📜  JavaScript 中的 find() 和 filter() 方法有什么区别?

📅  最后修改于: 2022-05-13 01:56:32.803000             🧑  作者: Mango

JavaScript 中的 find() 和 filter() 方法有什么区别?

find() 方法用于查找所选元素的所有后代元素。它通过遍历根到叶子来找到 DOM 树中的元素。

filter() 方法用于过滤所有元素并返回匹配的元素,不匹配的元素被移除。

唯一的区别是filter()方法搜索所有元素,而find()方法只搜索所有子元素。

  • 示例 1:此示例使用find() 方法搜索元素。
    
    
      
    
        
      
        
    
      
    
          
        

              GeeksForGeeks      

               

    Find() Method

               
              
    • GeeksforGeeks1.
    •         
    • GeeksforGeeks2.
    •         
                    
      1. GeeksforGeeks3.
      2.             
      3. GeeksforGeeks4.
      4.             
                          
        • GeeksforGeeks5.
        •                 
        • GeeksforGeeks6.
        •             
                
          
      
  • 输出:
  • 示例 2:当我们使用 filter() 方法进行搜索时所做的更改。
    
    
      
    
        
      
        
    
      
    
      
        

              GeeksForGeeks      

               

    Find() Method

           
              
    • GeeksforGeeks1.
    •         
    • GeeksforGeeks2.
    •         
                    
      1. GeeksforGeeks3.
      2.             
      3. GeeksforGeeks4.
      4.             
                          
        • GeeksforGeeks5.
        •                 
        • GeeksforGeeks6.
        •             
                
          
      
  • 输出:

让我们看看表格形式的差异-:

find()filter()
1.The find() method is used to find all the descendant elements of the selected element.The filter() method is used to filter all the elements
2.The find() method finds the element in the DOM tree by traversing through the root to the leaf.The filter() method returns the element that matches and removes the element that does not match.
3.The find() method search through all the child elements only.The filter() method search through all the elements
4.It does not execute the function for empty elements.The filter() method does not change the original array.
5.It does not change the original array.The filter() method does not execute the function for empty elements.
6.

Its syntax is -:

array.find(function(value, Index, array),thisValue)

Its syntax is -:

array.filter(function(value, Index, array), thisValue)

7.This method returns undefined if no elements are found.In filter() method a value is passed to the function as its this value