JAVASCRIPT 배열
배열 추가(변경) 방법 : 배열명[인덱스명] = "값";
.join() : 배열 사이에 넣을 값 지정 (default = ,) (타입 = String)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const city = ["서울", "부산", "인천"];
const printArr = () => {
for (let i = 0; i < city.length; i++) {
document.write(`배열 데이터[${i}] : ${city[i]}<br>`);
}
};
printArr();
city[3] = "대구";
document.write("<hr>" + city);
document.write(`<br>${typeof city}<br>`);
const join01 = city.join();
const join02 = city.join("-");
document.write(`조인 결과 1 : ${join01}, type : ${typeof join01}<br>`);
document.write(`조인 결과 2 : ${join02}, type : ${typeof join02}<br>`);
</script>
</body>
</html>
실행 결과
JAVASCRIPT 배열 (2)
배열명.push() : 배열 맨 뒤에 값을 추가
배열명.pop() : 배열 맨 뒤 값을 삭제
배열명.unshift() : 배열 맨 앞에 값을 추가
배열명.shift() : 배열 맨 앞에 값을 삭제
배열명.concat() : 해당 배열을 복사한다 (복사 후 추가도 가능)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let kdata = ["서울", "부산"];
document.write(`기본 배열 : ${kdata}<hr>`);
kdata.push("인천", "대구");
document.write(`push : ${kdata}<br>`);
kdata.pop();
document.write(`pop : ${kdata}<hr>`);
kdata.unshift("111", "222");
document.write(`unshift : ${kdata}<br>`);
kdata.shift();
document.write(`shift : ${kdata}<hr>`);
let data = kdata.concat("안녕", "하세요");
document.write(`concat : ${data}, type : ${typeof data}<br>`);
document.write(`shift : ${kdata}<hr>`);
</script>
</body>
</html>
실행 결과
JAVASCRIPT 배열 (3)
배열명.forEach(함수); : 단순출력, 연산 (return값을 가질 수 없다)
배열명.map(함수); : return값을 가질 수 있다
* 함수를 생성해서 넣을수도 있고, 생성된 함수를 넣을수도 있다
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const data = ["1111", "2222", "3333"];
for (let i = 0; i < data.length; i++) {
document.write(data[i] + "<br>");
}
document.write("<hr>");
// function t(d) {
// console.log(d);
// }
// const t = (d) => {
// console.log(d);
// };
// data.forEach(t);
data.forEach((d) => {
document.write(d + "<br>");
});
/*
function t02(d) {
return `<b style="color:blue;">${d}</b>`;
}
*/
const t02 = (d) => `<b style="color:red;">${d}</b>`;
const mapData = data.map(t02);
document.write("<hr>" + mapData + "<hr>");
const mapData02 = data.map((d) => `<b style="color:yellow;">${d}</b>`);
document.write("<hr>" + mapData02 + "<hr>");
</script>
</body>
</html>
실행 결과
JAVASCRIPT 배열 (4)
dic : 키와 값을 가진다
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let dic = { f0: 100, f1: 200 };
document.write(`기본 값 : ${dic}<br>`);
function test() {
document.write("test실행<br>");
}
dic.f2 = "값 추가";
dic["f3"] = "f3333";
dic.func = test;
document.write(dic + "<br>");
document.write(dic["f1"] + "<br>");
document.write(dic.f2 + "<br>");
document.write(dic.func + "<br>");
dic.func();
</script>
</body>
</html>
실행 결과
JAVASCRIPT 배열 (5)
배열명.filter(함수) : 데이터를 비교해서 해당하는 값만 돌려줌
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
const filter01 = (value, index) => {
console.log(`index : ${index}, value : ${value}`);
return value >= 50;
};
const result01 = data.filter(filter01);
document.write(result01 + "<br>");
const result02 = data.filter((value) => value <= 50);
document.write(result02 + "<br>");
</script>
</body>
</html>
실행 결과
JAVASCRIPT 배열 (6)
for (const 타입명 of 배열명) : forEach문
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
let userDB = [
{ id: "aaa", name: "홍길동", age: "20" },
{ id: "bbb", name: "김개똥", age: "30" },
{ id: "ccc", name: "고길동", age: "40" },
];
function init() {
//alert("실행");
const div = document.querySelector(".test");
let msg = `아이디 : ${userDB[0].id}<br>
이름 : ${userDB[0].name}<br>
나이 : ${userDB[0].age}<br>`;
div.innerHTML = msg;
const div2 = document.querySelector(".test2");
let msg2 = "";
for (const user of userDB) {
msg2 += `아이디 : ${user.id}<br>
이름 : ${user.name}<br>
나이 : ${user.age}<br>`;
}
div2.innerHTML = msg2;
}
</script>
</head>
<body onload="init()">
<div class="test"></div>
<hr />
<div class="test2"></div>
</body>
</html>
실행 결과
Quiz01
풀이 과정
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
let userInfo = [
{ id: "aaa", name: "홍길동", age: 20 },
{ id: "bbb", name: "김개똥", age: 30 },
{ id: "ccc", name: "고길동", age: 40 },
];
function init() {
const div1 = document.querySelector(".list");
let msg1 = `<h3>목록을 보여 줍니다</h3><hr>`;
div1.innerHTML = msg1;
// const div2 = document.querySelector(".search");
// let msg2 = `<hr><input placeholder="input id" id="search">`;
// div2.innerHTML = msg2;
// const div3 = document.querySelector(".delete");
// let msg3 = `<hr><input placeholder="input id">`;
// div3.innerHTML = msg3;
}
function listFunc() {
const list1 = document.querySelector(".list");
let msg01 = `<table border="1">`;
msg01 += `<tr>
<td>아이디</td> <td>이름</td> <td>나이</td>
</tr>`;
for (i = 0; i < userInfo.length; i++) {
console.log(userInfo[i].id);
msg01 += `<tr>
<td>${userInfo[i].id}</td> <td onclick="info('${userInfo[i].name}')">${userInfo[i].name}</td> <td>${userInfo[i].age}</td>
</tr>`;
}
msg01 += `</table>`;
list1.innerHTML = msg01;
}
function info(name) {
const list = document.querySelector(".list");
let msg;
for (i = 0; i < userInfo.length; i++) {
if (name == userInfo[i].name) {
msg = `<h2>아이디 : ${userInfo[i].id}</h2>
<h2>이름 : ${userInfo[i].name}</h2>
<h2>나이 : ${userInfo[i].age}</h2>
`;
}
}
list.innerHTML = msg;
}
function searchFunc() {
const search = document.querySelector("#search");
val = search.value;
const list1 = document.querySelector(".list");
let msg02 = `<table border="1">`;
msg02 += `<tr>
<td>아이디</td> <td>이름</td> <td>나이</td>
</tr>`;
for (i = 0; i < userInfo.length; i++) {
if (val == userInfo[i].id) {
msg02 += `<tr>
<td>${userInfo[i].id}</td> <td>${userInfo[i].name}</td> <td>${userInfo[i].age}</td>
</tr>`;
}
}
msg02 += `</table>`;
list1.innerHTML = msg02;
}
function deleteFunc() {
const d = document.querySelector("#delete");
val2 = d.value;
const list2 = document.querySelector(".list");
let msg03 = `<table border="1">`;
msg03 += `<tr>
<td>아이디</td> <td >이름</td> <td>나이</td>
</tr>`;
function rs(value) {
return value.id != val2;
}
const result = userInfo.filter(rs);
for (i = 0; i < result.length; i++) {
msg03 += `<tr>
<td>${result[i].id}</td> <td >${result[i].name}</td> <td>${result[i].age}</td>
</tr>`;
}
console.log(result.id);
msg03 += `</table>`;
list2.innerHTML = msg03;
}
function ad(asdf) {
console.log(asdf);
}
</script>
</head>
<body onload="init()">
<div class="list"></div>
<button id="btnList" onclick="listFunc()">모든 회원 보기</button>
<div>
<hr />
<input placeholder="input id" id="search" />
</div>
<div></div>
<button id="btnSearch" onclick="searchFunc()">특정 회원 조회</button>
<div></div>
<div>
<hr />
<input placeholder="input id" id="delete" />
</div>
<button id="btnDelete" onclick="deleteFunc()">특정 회원 삭제</button>
</body>
</html>
실행 결과
JAVASCRIPT 배열
setTimeout(함수, 시간); : 해당하는 함수를 실행하는데 걸리는 시간 지정 (1000 = 1초)
clearTimeout(setTimeout()) : setTimeout()을 취소하는 역할
Date() : 현재 시간을 알려주는 내장 함수
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const test = () => {
//alert("test 호출");
};
window.onload = () => {
//document.write("처음 실행<br>");
//setTimeout(test, 2000);
//document.write("2초 대기중...<br>");
};
let e;
const digClock = () => {
let today = new Date();
let time = today.getMonth() + 1 + "월";
time += today.getDate() + "일";
time += today.getHours() + "시";
time += today.getMinutes() + "분";
time += today.getSeconds() + "초";
document.getElementById("clock").innerHTML = time;
e = setTimeout(digClock, 1000);
};
const end = () => {
clearTimeout(e);
};
</script>
<div id="clock"></div>
<button onclick="digClock()">시작</button>
<button onclick="end()">종료</button>
</body>
</html>
실행 결과
JAVASCRIPT
setInterval(함수, 시간) : 지정한 시간이 지날때마다 함수를 반복 실행
clearInterval() : setInterval()을 취소하는 역할
.toLocalString() : 객체에 맞춰 문자열을 반환
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let myVar;
const start = () => {
myVar = setInterval(myTimer, 1000);
};
const myTimer = () => {
let d = new Date();
document.getElementById("time").innerHTML = d.toLocaleString();
};
const stop = () => {
clearInterval(myVar);
};
</script>
<p id="time"></p>
<button onclick="start()">start</button>
<button onclick="stop()">stop</button>
</body>
</html>
실행 결과
JAVASCRIPT
.insertAdjacentHTML("afterbegin") : 앞에 내용 추가
.insertAdjacentHTML("beforeend") : 뒤에 내용 추가
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
var cnt = 0;
const inner = () => {
cnt++;
let msg = `내용 : ${cnt}<br>`;
let txt = document.getElementById("txt");
txt.innerHTML = msg;
//txt.insertAdjacentHTML("afterbegin", msg);
//txt.insertAdjacentHTML("beforeend", msg);
};
</script>
<div id="txt">안녕하세요</div>
<button onclick="inner()">클릭</button>
</body>
</html>
실행 결과
JAVASCRIPT
.setAttribute() : 속성값 설정(추가)
document.createElement() : html태그요소를 추가(설정)하는 역할
태그명.appendChild() : 태그의 자식요소에 추가하는 역할
.remove() : 해당 태그 전체 삭제
.removeChild(객체) : 먼저 삭제할 객체를 지정해서 하나씩 삭제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let img;
function add() {
img = document.createElement("img");
console.log(img);
img.src = "image.png";
img.setAttribute("width", "100");
img.setAttribute("style", "height:100px border : 1px solid;");
document.getElementById("test").appendChild(img);
}
function addTB() {
let data = [
{ id: "aaa", name: "홍길동" },
{ id: "bbb", name: "김개똥" },
];
let table = document.createElement("table");
data.forEach((value) => {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.innerHTML = value.id;
tr.appendChild(td1);
var td2 = document.createElement("td");
td2.innerHTML = value.name;
tr.appendChild(td2);
table.appendChild(tr);
});
document.getElementById("test").appendChild(table);
}
function remove() {
let items = document.getElementById("test");
//document.getElementById("test").remove();
//items.remove();
items.removeChild(items.childNodes[0]);
//items.removeChild(items.childNodes[items.childNodes.length - 1]);
}
</script>
<p id="test"></p>
<a href="#" onclick="addTB()">테이블 추가</a>
<b onclick="add()">add 클릭</b>
<b onclick="remove()">이미지 삭제 클릭</b>
</body>
</html>
실행 결과
'javaScript' 카테고리의 다른 글
JAVASCRIPT 활용 (3) (0) | 2024.03.27 |
---|---|
JAVASCRIPT 활용 (0) | 2024.03.25 |
JAVASCRIPT 기초 (0) | 2024.03.22 |