프로그래밍/Dart

Dart List에 대해 그리고 함수들

autostar 2023. 4. 18.
반응형

List 타입

여러 값을 순서대로 한 변수에 저장할 때 사용.

List<String> variable = ['value1', 'value2', 'value3'];

// 리스트 값에 접근
print(variable[index]);
// 인덱스는 키 값입니다. 프로그래밍언어에서 보통 인덱스는 0 부터 시작합니다.

print 함수의 결과는 [value1, value2, value3] 이 됩니다.

 

List<String>  리스트 타입인데 꺽쇄 < > 사이에 String 이라고 적은것은 출력 하는 값의 타입이라고 할 수 있습니다.

위 코드 처럼 출력값은 스트링으로 한다고 지정합니다.

List<int> 라면 숫자를 반환해야 하겠죠. 값은 1,2,3,4 를 넣어야 합니다.

 

함수

List 에는 사용할수 있는 몇가지 함수가 있습니다.

add() 함수

List 에 값을 추가할 때 사용합니다.

리스트의 마지막에 값이 추가됩니다.

void main(){
List<String> list = ['I', 'study', 'dart'] ;

list.add('perfectly');

print(list);

// 결과 
// [I, study, dart, perfectly]

 

where() 함수

List 에 있는 값들을 순서대로 순회하면서 값을 필터링 하는데 사용합니다.

where( 안에서 필터링 하는 구문을 넣어줍니다.);

List<int> oldList = [1,2,3,4,5]

final newList = oldList.where(
  (name) => name == 3 || name == 4,
  );
  
  print(newList);
  }

결과는 (3, 4) 로 나옵니다.

응용해서 크거나 작거나 식을 넣어도 되겟죠?

### toList()

키 값의 객체를 리스트로 만들어주는 함수입니다.

위의 newList.toList() 로 해서 print 해보면

[3,4]  가 나오게 됩니다.

 

map () 함수

사용하는건 where 함수와 비슷합니다.

  List<int> oldList = [1,2,3,4,5];
  
final newList = oldList.map(
(name) => name+4);

print(newList);
// 모든값에 4을 더한 출력
// 결과 : (5, 6,7,8, 9)

reduce() 함수

역시 리스트를 순회하면서 매개변수에 입력된 하뭇를 실행합니다.

reduce() 함수는 순회할 때마다 값을 쌓아가는 특징이 있습니다. 

여태까지의 함수들은 Iterable 을 반환했지만 reduce 함수는 List 멤버의 타입과 같은 타입을 반환합니다

String reduce(String Function(String, String) combine)

Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

The iterable must have at least one element. If it has only one element, that element is returned.

Otherwise this method starts with the first element from the iterator, and then combines it with the remaining elements in iteration order, as if by:

음.. 아시겠죠? 함수명은 reduce 인데 그렇지 아니한 함수 인거 같습니다.

 

기초는 아닌거 같아서 패스하겠습니다.

 
반응형

'프로그래밍 > Dart' 카테고리의 다른 글

Dart 함수 형태  (0) 2023.04.19
Dart loop programming for 문 while 문  (0) 2023.04.19
Dart Nullable  (0) 2023.04.18
Dart Map과 Set  (0) 2023.04.18
Dart 기초 문법  (0) 2023.04.18

댓글