美文网首页
ES6中every和some的用法和区别

ES6中every和some的用法和区别

作者: biaobiaoBoom | 来源:发表于2020-12-28 22:33 被阅读0次

    相同:every和some都有三个参数,即item-当前项,index-当前项的索引值,array-数组本身;
    不同:every相当于逻辑关系中的且,只有所有参数都满足条件时,才返回true,一旦有一个不满足,则逻辑中断,返回false
    some相当于逻辑关系中的或,只要有一个参数满足条件,就中断遍历,返回true,若遍历完所有参数,没有符合的项,返回false

    some

    let 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

    let 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
    

    相关文章

      网友评论

          本文标题:ES6中every和some的用法和区别

          本文链接:https://www.haomeiwen.com/subject/owcxoktx.html