JS中some和every的区别和用法详解

来自:网络
时间:2023-05-17
阅读:

JS中some和every的区别和用法

some和every是数组中迭代的方法
相同点:some和every都有三个参数,即item→当前项,index→当前的索引值,array→数组本身;都可以遍历数组

不同点:

some相当于逻辑关系中的或,只要有一个参数满足条件,则中断遍历,返回true,如果遍历完所有参数,没有找到符合的项,即返回false;every相当于关系中的且,只有所有关系都满足条件时才返回true,一旦有一个不满足,则中断遍历,返回fasle。

通俗一点就是 some:一真即真,every:一假即假

let arr = [7, 6, 5, 4, 3, 2, 1,0];
    //一真即真,满足一个条件都返回 true
    console.log('some-→' + arr.some((item, index,array) => {
        console.log(array)
        return item > 6 // 返回true
    }));
    //一假即假,一个条件不满足就返回false
    console.log('every-→' + arr.every((item, index) => {
        return  item  // 返回 false
    }));

JS中some和every的区别和用法详解

总结:

some:循环遍历找到符合条件的值,一旦找到则不会继续迭代下去。

every:循环遍历是否符合条件,一旦有一个不符合条件,则不会继续迭代下去。

扩展:every 和 some 的区别

every() 方法用于检测数组的所有元素是否都符合指定条件,即 全真才真

every() 方法会遍历数组,当检测到有一个元素不满足指定条件时,直接返回 false,并且停止遍历,剩余元素不会再进行检测

const arr = [2, 4, 6, 8, 10]const res1 = arr.every(item => item < 5) // falseconst res2 = arr.every(item => item < 20) // true

特别注意: every() 不会对空数组进行检测,当数组为空时,直接返回 true

const res = [].every(item => item < 5)console.log(res); // true

some() 方法用于检测数组中是否有满足指定条件的元素,即 一真就真

some() 方法会遍历数组,当检测到有一个元素满足指定条件时,直接返回 true,并且停止遍历,剩余元素不会再进行检测

const arr = [2, 4, 6, 8, 10]const res1 = arr.some(item => item < 1) // falseconst res2 = arr.some(item => item < 5) // true

特别注意: some() 不会对空数组进行检测,当数组为空时,直接返回 false

const res = [].some(item => item < 1)console.log(res); // false
返回顶部
顶部