usage of some and every in js

  • Some usage: Check whether the array elements meet the specified conditions . If there is an element that meets the condition, the expression returns true, and the remaining elements will not perform detection; if there is no element that meets the condition, it returns false.
var arr = [ 1, 2, 3, 4, 5, 6 ]; 
		
console.log( arr.some( function( item, index, array ){ 
    console.log( 'item=' + item + ',index='+index+',array='+array ); 
    return item > 3; 
})); 
/*
    输出结果:
    item=1,index=0,array=1,2,3,4,5,6
    item=2,index=1,array=1,2,3,4,5,6
    item=3,index=2,array=1,2,3,4,5,6
    item=4,index=3,array=1,2,3,4,5,6
    true
*/
  • Usage of every: Check whether all elements of the array meet the specified conditions . The difference from some is that every needs to judge whether each element in the array satisfies the condition, and returns true only if all elements meet the condition; as long as one of them is not satisfied, it returns false;
var arr = [ 1, 2, 3, 4, 5, 6 ]; 
		
console.log( arr.every( function( item, index, array ){ 
    console.log( 'item=' + item + ',index='+index+',array='+array ); 
    return item > 3; 
}));
/*
    输出结果:
    item=1,index=0,array=1,2,3,4,5,6
    false
*/
  • The object is also the same
  • different, same

        -- Same as: Neither checks for an empty array; neither alters the original array.

        -- different:     

         · every: If an element in the array is detected to be unsatisfactory, the entire expression returns false, and the remaining elements will not be detected; otherwise, it returns true

         some: If one element satisfies the condition, the expression returns true, and the rest of the elements will not perform detection; if iterative is not satisfied, it returns false

  • Application scenario: whether to select all, whether a field exists in an array...

More common basic methods of js: Summary of some common methods of JS_❆VE❆的博客-CSDN博客

Guess you like

Origin blog.csdn.net/qq_45796592/article/details/131457464