Menu
Coddy logo textTech

리스트가 비어 있는지 확인하기

Coddy Dart 여정의 기초 섹션에 포함된 레슨 — 94개 중 54번째.

isEmptyisNotEmpty 속성은 리스트에 요소가 있는지 확인할 수 있게 해줍니다. 이 속성들은 boolean 값을 반환합니다.

숫자 목록을 생성하세요:

List<int> numbers = [1, 2, 3];
bool hasElements = !numbers.isEmpty;
print('List has elements: $hasElements');

위의 코드를 실행한 후 출력은 다음과 같습니다:

List has elements: true

빈 리스트를 생성하고 비어 있는지 확인하세요:

List<String> emptyList = [];
bool isEmpty = emptyList.isEmpty;
print('List is empty: $isEmpty');

위의 코드를 실행한 후 출력은 다음과 같습니다:

List is empty: true

또한 isNotEmpty 속성을 사용할 수 있습니다:

bool hasItems = numbers.isNotEmpty;
print('List has items: $hasItems');

위 코드를 실행한 후 출력은 다음과 같습니다:

List has items: true
challenge icon

챌린지

초급

이 챌린지에서는 Dart에서 리스트가 비어 있는지 확인하는 연습을 합니다. isEmpty 속성을 사용하여 리스트에 요소가 없는지 확인할 수 있습니다.

아래 코드를 완성하여 shoppingList가 비어 있는지 확인하세요. 비어 있다면 message 변수를 "Your shopping list is empty!"로 설정하세요. 그렇지 않으면 "You have items in your shopping list!"로 설정하세요.

예상 출력:

Your shopping list is empty!

치트 시트

isEmptyisNotEmpty 속성을 사용하여 리스트에 요소가 있는지 확인하세요. 이 속성들은 boolean 값을 반환합니다.

리스트가 비어 있는지 확인:

List<String> emptyList = [];
bool isEmpty = emptyList.isEmpty;
print('List is empty: $isEmpty'); // List is empty: true

리스트에 요소가 있는지 확인:

List<int> numbers = [1, 2, 3];
bool hasItems = numbers.isNotEmpty;
print('List has items: $hasItems'); // List has items: true

부정을 사용한 대안 방법:

bool hasElements = !numbers.isEmpty;

직접 해보기

void main() {
  // 이 쇼핑 리스트는 이미 정의되어 있습니다
  List<String> shoppingList = [];
  
  // TODO: shoppingList가 비어 있는지 확인하세요
  // 비어 있으면 message를 "Your shopping list is empty!"로 설정하세요
  // 그렇지 않으면 message를 "You have items in your shopping list!"로 설정하세요
  String message = "";
  
  // 이것은 결과를 표시합니다
  print(message);
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

기초의 모든 레슨