跳出forEach循环的方式

141 阅读1分钟

使用some

循环体内返回true时,跳出循环

this.suppliers.some(index => {
      // some为当循环内部返回true的时候,跳出整个循环。
      // 若该数组中拥有与参数相等的值,返回true
      if (index === Id) {
        isSuppliers = true;
        return true;
      }
    });

every为循环体返回false时,跳出循环

this.suppliers.every(index => {
      if (index === Id) {
        isSuppliers = true;
        return false;
      }
    });

break无法跳出循环

如果写成:

this.suppliers.forEach(index => {
      if (index === Id) {
        isSuppliers = true;
        break;
      }
    });

break只会跳出if循环体,而不会跳出forEach循环体,所以依旧会一直循环。
且无法在forEach循环体中使用break。