본문 바로가기
2019/JavaScript

JS Array

by SOLYI 2019. 12. 6.

 

  • 배열 생성 방법
1
2
3
4
5
6
7
8
9
10
// 1. 배열 선언만. 자료 없음
var d1=[];  
 
// 2. 2칸 생성만 선언
var d2=new Array(2);  
 
// 3-1. 4와 2가 들어갈 배열 선언
var d3=new Array(4,2); 
// 3-2. 3개가 들어갈 배열 선언
var d4=new Array("a","b","c"); 
  • 출력 방법
1
2
3
4
5
6
7
8
9
10
11
12
13
let arr=["a1","a2","a3"];
console.log(arr[0]);  //a1
 
let arr3=new Array('z1''z2''z3');
console.log(arr3[0]); //z1
console.log(arr3[1]); //z2
console.log(arr3[2]); //z3
 
let arr1=["choi""kim""lee"];
console.log(arr1);
for(let i in arr1){
      console.log(i, arr1[i]);
}   
  • 타입 확인 / 배열 길이 확인
1
2
3
4
5
6
7
8
9
var d1=[];  //배열 선언만. 자료 없음
var d2=new Array(2);  //2칸 생성만 선언
var d3=new Array(4,2); //4와 2가 들어갈 배열 선언
var d4=new Array("a","b","c"); //3개가 들어갈 배열 선언
 
console.log(typeof(d1), d1.length); //0
console.log(typeof d2, d2.length); //2
console.log(typeof d3, d3.length); //2
console.log(typeof(d4), d4.length); //3

 

  • 배열인지 확인 하는 방법
1
2
let arr2=new Array(2); 
console.log(Array.isArray(arr2)); //true
  • 배열에 추가하기 push / 배열에서 꺼내오며 삭제하기 pop
1
2
3
4
5
6
7
8
9
10
11
12
13
let arr=["z1","z2","z3"];
arr.push("z4");
arr.push("hello");
 
while(arr.length>0){
    console.log(arr.pop()); 
}
//arr 안 자료가 모두 출력 되면 멈춘다.
 
//혹은 아래 방법도 가능.
console.log(arr.pop());        
console.log(arr.pop());
console.log(arr.pop());
  • 배열 이어붙이기 concat /  사이에 문자 출력하기 join
1
2
3
4
5
6
var arr=['a','b','c'];
var result=arr.concat(1,2,3,4);
console.log(result);
 
var jarr=arr.join('/');
console.log(jarr);
  • splic splice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let arr1=["choi","kim","lee","park"];
let arr2=arr1.slice(1,3); //1부터 3-1까지
console.log(arr1); //전부 출력
console.log(arr2); //kim,lee
 
arr2[0]="haha";
console.log(arr1);
console.log(arr2);
 
let arr3=["z1","z2","z3","z4"]
arr3.splice(02); //0부터 2-1까지 짤라낸다.  //원본을 수정
console.log(arr3.length);
console.log(arr3);
 
let arr4=["h1","h2","h3","h4"];
//        arr4.splice(2,0,"p1","p2");  //h1,h2,p1,p2,h3,h4
            //2번째 칸부터 0개만큼 삭제하고 삽입
arr4.splice(2,1,"p1","p2");    //h1,h2,p1,p2,p4
            //2번째칸부터 1개만큼 삭제하고 삽입
console.log(arr4);
 
  • 정렬 sort
1
2
3
4
5
6
7
8
let arr=["choi","kim","lee","park"];
let jumsu=[20504020060,300,1,2,3,500,30];
 
arr.sort();
jumsu.sort(); 
//작은수부터 큰수가 아니라, 앞자리가 작은것부터... 
// 1,2,20,200,3,30,,,,
 
 
  • 진짜 정렬하는 방법 compare
1
2
3
4
5
6
7
8
9
//문자역순 (z -> a)
arr.sort(function(data1, data2){
    return -(data1.localeCompare(data2));
});
 
//내림차순 (6 -> 1);
jumsu.sort(function(data1, data2){
    return -(data1-data2);
});
 
  • 역순 reverse
    • arr.reverse();
  • indexOf
1
2
3
let arr=["choi","kim","lee","park"];
console.log(arr.indexOf("kim"));  //1
console.log(arr.indexOf("haha")); //-1
반응형

'2019 > JavaScript' 카테고리의 다른 글

JS add Event Listener (set Attribute)  (0) 2019.12.09
JS getElement  (0) 2019.12.09
JS Date  (0) 2019.12.06
JS 숫자  (0) 2019.12.06
JS String  (0) 2019.12.06