Java Script/MDN 정리
자바스크립트 첫걸음 ~ 배열
Zin0_0
2020. 7. 23. 20:23
반응형
배열
- 배열 만들기
var sequence = [1, 1, 2, 3, 5, 8, 13]; var random = ['tree', 795, [0, 1, 2]];
- 위와 같이 배열 안에 모든 항목을 한번에 저장할 수 있다. (배열 안에 배열도 가능)
유용한 배열 Method
문자열을 배열로, 배열을 문자열로 변환하기
split()
var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle'; var myArray = myData.split(','); myArray;
join()
var myNewString = myArray.join(','); myNewString;
- 조인 안에 문자열 파라메터를 입력해서, 배열 인덱스 사이에 파라메터를 넣어 문자열로 만든다.
toString()
var dogNames = ['Rocket','Flash','Bella','Slugger']; dogNames.toString(); //Rocket,Flash,Bella,Slugger
- toString() 메소드는 join()과 달리 매개변수가 필요 없어서 더 간단하지만, 제한이 더 많다.
- 배열에 item을 추가하고 제거하기
var cityArr = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];
- push()
cityArr.push('Cardiff'); cityArr; cityArr.push("Bradford", "Brighton"); cityArr;
- method 호출이 완료되면 배열의 item이 변한 것을 확인할 수 있다. (length 반환)
var newLen = cityArr.push("Bradford", "Brighton"); cityArr; newLen;
- pop()
cityArr.pop();
- unshift()와 shift()는 push()와 pop()과 유사하게 동작한다. 다만, 배열의 끝이 아닌 제일 처음 부분의 item을 추가하거나 제거한다.
myArray.unshift('Edinburgh'); myArray; var removedItem = myArray.shift(); myArray; removedItem;
- push()
Active learning: Printing those products!
링크
var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;
list.innerHTML = '';
totalBox.textContent = '';
var products = ['Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'];
for(var i = 0; i < products.length; i++) {
var infos = products[i].split(':');
total += Number(infos[1]);
itemText = infos[0]+ ' — $' + infos[1];
var listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
totalBox.textContent = 'Total: $' + total.toFixed(2);
var list = document.querySelector('.output ul');
var searchInput = document.querySelector('.output input');
var searchBtn = document.querySelector('.output button');
list.innerHTML = '';
var myHistory = [];
searchBtn.onclick = function() {
if (searchInput.value !== '') {
myHistory.unshift(searchInput.value);
list.innerHTML = '';
for (var i = 0; i < myHistory.length; i++) {
itemText = myHistory[i];
var listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
if (myHistory.length >= 5) {
myHistory.pop();
}
searchInput.value = '';
searchInput.focus();
}
}
반응형