wasup

JavaScript) 배열의 함수 본문

IT/html, css, script

JavaScript) 배열의 함수

wasupup 2021. 4. 14. 16:58
반응형

1. push(); : 배열 끝에 요소를 추가.

//Array.push();
var arr6 = ['a', 'b', 'c'];

arr6.push('d');
arr6.push(function(){alert('배열.push() 함수 호출')});
arr6.push(function(x, y){alert( x + ' + ' + y + ' = ' + x+y)});
document.write('<ul>');
for(var i = 0; i < arr6.length; i++){
	document.write('<li>'+typeof(arr6[i])+ '=' + arr6[i] + '</li>');
}
document.write('</ul>');

 


2. pop(); : 배열의 마지막 요소를 꺼내온 후 삭제

//Array.pop();
var last = arr6.pop();
document.write(last+'<br/>');
document.write('<ul>');
for(var i = 0; i < arr6.length; i++){
	document.write('<li>'+typeof(arr6[i])+ '=' + arr6[i] + '</li>');
}
document.write('</ul>');

var last = arr6.pop();
document.write('<hr/>'+last+'<br/>');
document.write('<ul>');
for(var i = 0; i < arr6.length; i++){
	document.write('<li>'+typeof(arr6[i])+ '=' + arr6[i] + '</li>');
}
document.write('</ul>');


3. shift(); : 배열의 첫 번째 요소를 꺼내온 후 제거

//Array.shift();
var first = arr6.shift();
document.write('<ul>');
for(var i = 0; i < arr6.length; i++){
	document.write('<li>'+typeof(arr6[i])+ '=' + arr6[i] + '</li>');
}
document.write('</ul>');


4. concat(); : 두 개의 배열을 하나로 합치는 함수

//Array.concat();
var arr7 = ['a', 'b', 'c'];
var arr8 = [1, 2, 3];
var arr9 = arr7.concat(arr8);//arr9는 arr7에 arr8을 합친 것.
document.write('<ul>');
for(var i = 0; i < arr9.length; i++){
	document.write('<li>'+typeof(arr9[i])+ '=' + arr9[i] + '</li>');
}
document.write('</ul>');


5. join(); : 배열의 요소 사이에 원하는 데이터를 삽입

//Array.join();
var arr9 = arr9.join('*');
document.write('<ul>');
for(var i = 0; i < arr9.length; i++){
	document.write('<li>'+typeof(arr9[i])+ '=' + arr9[i] + '</li>');
}
document.write('</ul>');


6. reverse(); : 배열을 역순으로 뒤집는 함수

//Array.reverse();
arr9 = ['a', 'b', 'c']; //c, b, a로 나오게 reverce사용
arr9.reverse();
document.write('<ul>');
for(var i = 0; i < arr9.length; i++){
	document.write('<li>'+typeof(arr9[i])+ '=' + arr9[i] + '</li>');
}
document.write('</ul>');


7. sort(); : 배열을 정렬

//Array.sort();
arr9 = [3, 2, 4, 1, 5, 8, 7, 9, 6];
arr9.sort();
document.write(arr9 + '<br/>');


8. slice(); : 배열의 일부분을 반환

//Array.slice();
arr9 = [1, 2, 3, 4];
var example = arr9.slice(0, 3);
document.write('arr9.slice(0, 3); = ' + example + '<br/>');
var example = arr9.slice(0, -1);
document.write('arr9.slice(0, -1); = '+ example + '<br/>');
var example = arr9.slice(1, -1);
document.write('arr9.slice(1, -1); = '+ example + '<br/>');


9. splice(); : 배열의 값을 추가하거나 제거해서 반환

//Array.splice();
var arr10 = ['a', 'b', 'c', 'd'];
var example = arr10.splice(1, 2);//arr10에서 1, 2번 삭제
document.write(arr10 + '<br/>');//남은 값 a, d출력
document.write(example + '<br/>');//삭제한 값 b, c출력


반응형
Comments