반응형

 

Array객체

    요소의 추가/삭제/결합/정렬 등이 가능

    배열을 생성할 때는 리터럴을 이용하는 것을 권장함

 

    [] 대괄호를 이용하여 생성(리터럴)

    new Array(); 배열 생성

    new Array('test', 'hello'); 지정된 요소로 생성

    new Array(10); 사이즈 지정

 

주요멤버

concat(arr) : 기존 배열에 arr 연결

join(del) : 배열의 요소를 del 구분문자 삽입

slice(start [, end]) : start~end-1번째 요소를 잘라옴

slice(start, cnt [, rep [, …]]) : start+1 ~ start+cnt+1번째 요소를 rep, ... 치환

pop() : 배열의 마지막 요소를 가져오고 해당 값은 삭제함

push(data) : 배열 마지막에 data요소를 추가

shift() : 배열의 번째 요소를 가져오고 해당 값은 삭제

unshift(data1 [, data2, ...]) : 배열 번째에 요소를 추가

reverse() : 배열의 요소를 역순으로 정렬

sort([func]) : 요소를 오름차순으로 정렬

length : 배열의 사이즈

toString() : [요소, 요소, ...] 형식의 문자열로 가져옴

 

Array객체 사용 주의할

  1. concat, slice, join, toString 제외한 메서드는 원본 데이터가 영향을 받음
  2. 배열의 내용 확인은 toString()메서드를 이용하면 편리하다.
  3. sort메서드에는 사용자 정의 함수를 지정할 있다.
    1. 사용자 정의 함수를 사용할 경우 지켜야할 규칙 가지
      1. 인수는 가지(비교할 배열 요소)
      2. 번째 인수가 번째 인수보다 작은 경우는 음수, 수일 경우 양수를 반환한다.

var ary = [5, 25, 10];

document.writeln(ary.sort());

document.writeln(ary.sort(

function(x, y) {return x - y;}));

 

array.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Array객체</title>
</head>
<body>
<pre>
<script type="text/javascript">
var ary1 = ['gildong''sunsin''youngsu''mina''taesu'];
var ary2 = ['sumi''woosung''wonbin''suyoung'];
 
document.writeln(ary1.concat(ary2));
document.writeln(ary1.join('/'));
document.writeln(ary1.slice(1));
document.writeln(ary1.slice(12));
document.writeln(ary1.splice(12'suyeon''eunjung'));
document.writeln(ary1);
 
document.writeln(ary1.pop());
document.writeln(ary1);
document.writeln(ary1.push('hyunsu'));
document.writeln(ary1);
document.writeln(ary1.shift());
document.writeln(ary1);
document.writeln(ary1.unshift('minsu''sunho'));
document.writeln(ary1);
 
document.writeln(ary1.reverse());
document.writeln(ary1);
document.writeln(ary1.sort());
document.writeln(ary1);
 
document.writeln(ary1.length);
document.writeln(ary1.toString());
</script>
</pre>
</body>
</html>
cs
반응형

'교육자료 > Javascript' 카테고리의 다른 글

12. RegExp 객체(정규 표현식)  (0) 2019.05.09
11. Date 내장객체  (0) 2019.05.09
09. Math 내장객체  (0) 2019.05.09
08. Number 내장객체  (0) 2019.05.09
07. String 내장객체  (0) 2019.05.09

+ Recent posts