js中some和every用法

  • some的用法:检测数组元素是否有符合指定条件。如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测;如果没有满足条件的元素,则返回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
*/
  • every的用法:检测数组所有元素是否都符合指定条件。跟some不同点在于,every要判断数组中是否每个元素都满足条件,只有都满足条件才返回true;只要有一个不满足就返回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
*/
  • 对象也是同理
  • 异、同

        -- 同: 都不会对空数组进行检测;都不会改变原始数组。

        -- 异:     

         · every:如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测;反之返回true

         · some:如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测;如果迭代完没有满足的则返回false

  • 应用场景:是否全选、一个字段是否存在在某个数组中…

更多js常用基本方法:JS一些常用方法汇总_❆VE❆的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_45796592/article/details/131457464