JavaScript/이론
[Javascript] Array
sirius
2021. 3. 18. 10:18
배열은 리터럴 방식, 클래스 방식으로 생성 할 수 있으며, 리터럴 방식으로 실행되면 클래스 방식으로 치환되어 실행
//리터럴 방식
var array = ['test1', 'test2', 'test3', 'test4'];
//클래스 방식
var array = new Array('test1', 'test2', 'test3', 'test4');
메서드 | 설명 |
join() | 배열을 문자열로 변환하여 반환 |
split() | 문자열을 배열로 변환하여 반환 |
push() | 배열 마지막 위치에 배열 요소 추가 |
unshift() | 배열 첫 번째 위치에 배열 요소 추가 |
splice() | 배열 N 번째 위치에 배열 요소 추가 |
shift() | 첫 번째 요소 삭제되며 삭제된 값을 반환 |
pop() | 배열의 마지막 번째 요소를 삭제하며 삭제된 값을 반환 |
sort() | 배열의 요소를 정렬 |
//join() 배열을 문자열로 만들기
var array = ['test1', 'test2', 'test3', 'test4'];
var result = array.join("-");
console.log(result);
//split() 문자열을 배열로 만들기
var str = 'test1-test2-test3-test4';
var resultArray = str.split('-');
console.log(resultArray);
//push() 특정 위치에 배열 요소 추가
var array = ['test1', 'test2', 'test3', 'test4'];
array.push('test5');
console.log(array);
//unshift() 첫 번째 위치에 배열 요소 추가하기
var array = ['test1', 'test2', 'test3', 'test4'];
array.unshift('test0');
console.log(array);
//splice() 배열의 N 번째 위치에 배열 요소 추가하기
//배열.splice(start, deleteCont, [,element]);
//start : 추가 또는 삭제할 배열 요소의 시작 위치
//deleteCount : start부터 시작하여 삭제할 배열 요소의 개수, 요소를 추가할 때는 0을 적용
//element : 추가 요소
var array =['test1', 'test2', 'test3', 'test4'];
array.splice(3, 0, 'test3-1');
console.log(array);
//splice()를 응용하여 N번째 배열 요소 삭제하기
var array = ['test1', 'test2', 'test3', 'test4'];
array.splice(2,1);
console.log(array);
//shift() 첫 번째 요소 삭제가 되고 삭제된 값이 리턴
var array = ['test1', 'test2', 'test3', 'test4'];
console.log(array.shift());
console.log(array);
//pop() 마지막 요소가 삭제되고 삭제된 값이 리턴
var array = ['test1', 'test2', 'test3', 'test4'];
console.log(array.pop());
console.log(array);
//////////////////////////////////////////////////////////
var name = ['test1', 'test2', 'test3', 'test4'];
for(var i=0; i < name.length; i++) {
name[i] = name[i] + ' is hello';
}
console.log(name);
//////////////////////////////////////////////////////////
//Array.foreach()
//배열 전체를 돌며 해당 배열의 요소에 직접 어떤 작업을 수행하고 싶을 때 적합.///
var name = ['test1', 'test2', 'test3', 'test4'];
name.forEach(function(value, index, array) {
name[index] = value + ' is hello';
});
console.log(name);
//Array.map()
//기존에 선언된 배열의 데이터를 활용하여 새로운 배열을 생성할 때 사용.
var name =['test1', 'test2', 'test3', 'test4'];
var newName = name.map(function(value, index, array) {
return value + ' is hello';
});
console.log(name);
console.log(newName);
//Array.filter()
//특정 케이스만 filter 체크하여 새로운 배열을 만든다.
var name = ['aa', 'bb', 'cc', 'dd', 'yujin' ];
var newName = name.filter(function(value, index, array) {
return !!~value.search(/[ab]+/);
});
console.log(newName);