find用法

163 阅读1分钟
        // find 用找满足条件的数组中一个元素 
        // 找到了之后 不会再继续往下遍历 
        // 代码中 找到了 你需要返回true 
        // forEach 也可以做遍历 但是 不能被中断 打断 (for循环不一样!! )
        // forEach 做遍历的时候 是不能被打断 中断  break!!!!
        // for 和 foreach有什么区别  1 都是循环  2 for循环可以被中断 但是 foreach不可以!!
        // find 返回符合 条件的数组元素。
        const arr = [
            { username: '悟空', height: 70 },

            { username: '八戒', height: 60 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },

            { username: '龙马', height: 30 },
        ];
        // // 要求的 返回   身高是 60的 那一个对象
        // let obj;
        // arr.forEach((value) => {
        //   if (value.height === 60) {
        //     // 找到了
        //     obj = value;
        //     return
        //   }
        //   console.log(value);
        // });
        // console.log(obj);
        // const obj = arr.find((value) => {
        //   console.log(value);
        //   if (value.height === 60) {
        //     return true;
        //   } else {
        //     return false;
        //   }
        // });
        const obj = arr.find((value) => value.height === 60);
        console.log(obj);

image.png