반복문으로 slice 사용

민규·2025년 10월 27일

자바스크립트

목록 보기
2/3

배열안의 객체를 반복문을 돌리고 싶을 경우
for...of 를 사용하게 되면 배열안에 있는 여러개의 객체를 각각 반복문을 돌릴 수 있다

예시

```
var sample1 = [
				{ id="1", name="Gil-Dong_Hong", age="24" }
              ]
              ...

const arrayList = [sample1, sample2, sample3];

for(const list of arrayList){ 
	for(const item of list) {
    	if(item.name){
          // indexOf로 '_' 있는지 찾아서 반환해줌 (ex: 1)
          const showName = item.name.indexOf('_');
          
          if(showName >= 0){
          	item.name = item.name.slice(0, showName+4);
          } else {
          	item.name = '';
          }
        }
    }   
}

/*
	- 첫 for문에서 arrayList안에 있는 객체수 만큼 반복문을 돌림
    - list로 선언한 변수의 객체들의 안에 있는 item으로 선언하여서 객체마다 반복문을 돌림
    - item의 특정 데이터만 혹은 분기처리 하고싶을땐 item.name 이런식으로 사용하면됨
*/
```
profile
분발해 나의 뇌

0개의 댓글