o 문자열 함수
let str = "Gone With The Wind"
document.writeln(str);
document.writeln(str.length);//18
document.writeln(str.charAt(0));//문자열의 0번째 글자 "G" 출력
document.writeln(str.charAt(17));//"d" 마지막 글자
document.writeln(str.charAt(str.length - 1));
document.writeln(str.toLowerCase());//전부 소문자 치환
document.writeln(str.toUpperCase());//전부 대문자 치환
document.writeln(str.replace("n", "N"));//소문자 n을 대문자 N으로, 맨 처음 나오는 해당글자 하나만
document.writeln(str.replace(/n/g, "M"));//n을 M으로 전체변경
//글자 자르기
document.writeln(str.substring(6, 12));//ith Th 6~(12-1)번째 글자까지 출력, 0부터 카운트하여 문자열 맨 끝 추가된 꼬리말 한칸 뺀 곳까지 출력
document.writeln(str.substring(10, 13));//"The" 0부터 카운트 시작하여 가져오고 싶은 문자열 순서+1하여
//맨 앞글자 자르기 "G",
document.writeln(str.substring(0, 1));
//맨 마지막 글자 자르기 "d"
document.writeln(str.substring(17, 18));
document.writeln(str.substring((str.length-1), str.length));
//문자열 분리하기 substring과 동일
document.writeln(str.slice(10, 13));//"The"
//문자열의 맨앞맨뒤 공백제거
document.write("#" + " s k y ".trim() + "#");
document.write("<hr>");
//문자열 합치기
let text1 = "Hello";
let text2 = "world";
let text3 = text1.concat(text2);
document.write(text3); //"Helloworld"
document.write("<hr>");
//4칸을 기준으로 빈칸은 *으로 앞에서부터 채우기
let text5 = "9";
document.write(text5.padStart(4, "*")); //***9
document.write("<hr>");
//4칸을 기준으로 빈칸은 *으로 뒤에서부터 채우기
let text6 = "8";
document.write(text6.padEnd(4, "*")); //8***
document.write("<hr>");
//.split()문자열을 배열로 변경<<체크필요
o계산기
<head>
<title>02_계산기.html</title>
<style>
.txt{
border: 2px solid #ccffff;
text-align: right;
font-weight: bold;
font-size: 20px;
color: black;
height: 30px;
background: #f5f5f5;
}
</style>
</head>
<body>
<h3>미니 계산기</h3>
<form>
<table border="1">
<tr>
<td colspan="4">
<input type="text" name="result" id="result" size="20" value="0" readonly class="txt">
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value=" <x " onclick="backspace()">
</td>
<td colspan="2">
<input type="button" value=" c " id="result" onclick="cls()">
</td>
</tr>
<tr>
<td><input type="button" value=" 7 " onclick="inputData(7)"></td>
<td><input type="button" value=" 8 " onclick="inputData(8)"></td>
<td><input type="button" value=" 9 " onclick="inputData(9)"></td>
<td><input type="button" value=" / " onclick="operator('/')"></td>
</tr>
<tr>
<td><input type="button" value=" 4 "onclick="inputData(4)"></td>
<td><input type="button" value=" 5 "onclick="inputData(5)"></td>
<td><input type="button" value=" 6 "onclick="inputData(6)"></td>
<td><input type="button" value=" x " onclick="operator('*')"></td>
</tr>
<tr>
<td><input type="button" value=" 1 "onclick="inputData(1)"></td>
<td><input type="button" value=" 2 "onclick="inputData(2)"></td>
<td><input type="button" value=" 3 "onclick="inputData(3)"></td>
<td><input type="button" value=" - " onclick="operator('-')"></td>
</tr>
<tr>
<td><input type="button" value=" = " onclick="compute()"></td>
<td><input type="button" value=" 0 "onclick="inputData(0)"></td>
<td><input type="button" value=" . "></td>
<td><input type="button" value=" + " onclick="operator('+')"></td>
</tr>
</table>
</form>
<script>
//1) C버튼 클릭 시 id=result에 0 대입
function cls(){
document.getElementById("result").value = 0;
}//cls end
//2) 클릭한 숫자 버튼에 맞는 숫자 출력
function inputData(su) {
//전달받은 su변수값을 result에 대입
//기존입력값에 su값을 더해 출력
//document.getElementById("result").value += su;
//버튼입력시 초기값"0"이 출력되지 않게 하기 위해서 id=result값 "0123"을 숫자열로 바꾸면 123이 됨
//document.getElementById("result").value = Number(document.getElementById("result").value + su);
su = Number(document.getElementById("result").value + su);
document.getElementById("result").value = su;
}//inputData() end
function backspace() {
//3) <x버튼을 클릭하면 id=result값에서 마지막 글자부터 순서대로 지우기
//id=result값에서 마지막 글자만 제외시키고 다시 대입
//단, 자릿수가 한 개인 값은 0으로 대입
/*내가하다만것
let result = String(document.getElementById("result").value);
let len = result.length;
String(result) = result.substring(0, len-1);
if (len == 1 ) {
result = 0;
}
document.getElementById("result") = result;
*/
//a) id=result값을 가져와 변수 result에 넣기
let result = document.getElementById("result").value;
//alert(result);
//변수 result의 길이 확인
//alert(result.length);
//b) 변수 result의 길이를 변수 len에 넣기
let len = result.length;
// alert(result.substring(0, 2));
//처음 글자부터 마지막 글자를 제외하고 문자열 가져오기
//alert(result.substring(0, len-1));
//c) 분리된 b문자열을 다시 id=result에 대입
//단, 글자수가 1이면 0으로 다시 대입
if(len==1) {
document.getElementById("result").value=0;
}else {
document.getElementById("result").value= result.substring(0, len-1);
}//if end
}//backspace() end
//4)연산에 필요한 전역변수 선언
let op;//연산기호 기억
let num1; //사용자가 입력한 첫번째 수
let num2; //사용자가 입력한 두번째 수
function operator(kind) {
//5) 클릭한 연산기호를 전역변수 op에 저장
op = kind;
//alert(op);
//6)현재 id=result가 가지고 있는 값을 num1에 저장
num1 = Number(document.getElementById("result").value);
//7)두번째 수를 입력받기 위해 id=result값 초기화하기
cls();
}//operator() end
function compute() {
// alert(op);
// alert(num1);
//실제 계산을 해 결과값 출력
//8)계산에 필요한 두번째 수를 num2에 저장
num2 = Number(document.getElementById("result").value);
//9)계산해서 결과 출력, 괄호 안 입력값 계산해서 출력하는 함수 eval()활용
document.getElementById("result").value=eval(num1 + op + num2);
}//compute() end
</script>
</body>
o js에서 스타일 접근
<body>
<h3>자바스크립트에서 스타일 접근</h3>
<div id="mydiv" style="position: relative;
top 10px;
left: 20px;
width: 150px;
height: 70px;
background-color: red;">대한민국</div>
<hr>
<input type="button" value="mydiv의 style속성" onclick="test1()">
<input type="button" value="mydiv의 style변경" onclick="test2()">
<hr>
<img src="../../images/devil.png" id="myimg">
<hr>
<input type="button" value="이미지변경" onclick="test3()">
<script>
function test1() {
//[object HTMLDivElement]
//alert(document.getElementById("mydiv"));
//순수 자바스크립트 스타일 접근
//[object CSSStyleDeclaration]
//alert(document.getElementById("mydiv").style);
//jQuery에서 스타일 접근(추천)
//$("#mtdiv").css()
alert(document.getElementById("mydiv").style.top);
alert(document.getElementById("mydiv").style.left);
alert(document.getElementById("mydiv").style.width);
alert(document.getElementById("mydiv").style.height);
alert(document.getElementById("mydiv").style.backgroundColor);
alert(document.getElementById("mydiv").style.position);
}//test1() end
function test2() {
document.getElementById("mydiv").style.top = "100px";
document.getElementById("mydiv").style.left = "150px";
document.getElementById("mydiv").style.width = "400px";
document.getElementById("mydiv").style.height = "300px";
document.getElementById("mydiv").style.backgroundColor = "green";
document.getElementById("mydiv").style.position = "absolute";
}//test2 end
function test3() {
document.getElementById("myimg").src="../../images/angel.png";
}//test3() end
</script>
</body>
o this
<h3>this</h3>
<form name="myform" id="myform" onsubmit="return test6(this.form)">
<input type="button" name="btn1" id="btn1" value="버튼1" onclick="test1()">
<input type="button" name="btn2" id="btn2" value="버튼2" onclick="test2('this')">
<hr>
<!--this 명령어-->
<input type="button" name="btn3" id="btn3" value="버튼3" onclick="test3(this)">
<!--this.value 자신의 요소가 가지고 있는 실제 값 (value="")-->
<input type="button" name="btn4" id="btn4" value="버튼4" onclick="test4(this.value)">
<!--this.form 자신의 요소가 가지고 있는 폼 (form name=myform)-->
<input type="button" name="btn5" id="btn5" value="버튼5" onclick="test5(this.form)">
<hr>
<!--onsubmit이벤트는 리턴값이 true이면 전송-->
<input type="submit" value="전송">
<hr><!--this키워드는 폼컨트롤요소에서 사용-->
<a href="#" onclick="test7(this)">아이티윌</a>
</form>
<script>
/*
[this]
-변수X, 명령어o
-자기 자신의 요소 지칭
-폼 컨트롤 요소에서만 사용가능
예) <a href="" onclick="test(this)"></a>
여기에서 this는 쓰레기값이므로 주의!!
*/
function test1() {
//1) name접근 (비추)
let f=document.myform;
//alert(f);//[object HTMLFormElement]
//alert(f.btn1);//[object HTMLInputElement]
//alert(f.btn1.value);//버튼1
//2)id접근(추천)
alert(document.getElementById("btn1").value);//버튼1
}//test1() end
function test2(obj) {
alert(obj);//'this'
}//test2() end
function test3(obj) {//obj에 위에서 this 키워드가 들어갔다
alert(obj);//[object HTMLInputElement]
alert(obj.value);//버튼3
}//test3() end
function test4(val) {
alert(val);//버튼4
}//test4 end
function test5(f) {
alert(f);//[object HTMLFormElement] 여기서는 form name=myform
alert(f.btn5);//[object HTMLInputElement]
alert(f.btn5.value);//버튼5
}//test5 end
function test6(f){
alert(f);//[object HTMLFormElement]
//위에서 매개변수에 this.form을 넣으면 undefined를 나온다.
//>>this가 form인 myform이고 이것이 속한 다른 폼이 존재불가능하기 때문에
function test7(obj) {
alert(obj);
}//test7() end
}
</script>
o JSON
<script>
/*
● XML문법
- 여는태그와 닫는태그로 구성>>html이 차용
- custom tag(사용자 정의 태그) 기반
- 환경설정 파일 작성, 안드로이드 기반 앱개발시 View단 구성
예) <database>
<driver>OracleDriver</driver>
<username>system</username>
<password>1234</password>
</database>
● JSON (JavaScript Object Notation)
- 문자단위 통신(비동기식 방식:페이지 일부분만 서버에서 받아오려고 할 때, 문자단위 통신)에서 XML를 대체하는 포맷이다
- AJAX, NoSQL DB등에서 주로 사용하는 포맷(표기법)
- 배열을 객체화
● JSON 기본 구조
- 속성:값 쌍으로 데이터가 구성되어 있다
- 속성(name, key, property), 값(value, data)
- name구성시 "" 기호는 생략가능하다
- {}안에 데이터를 저장한다
- 형식) {name:value, "name":value, 'name':value, ~~~}
- 예) {driver:"OracleDriver", "username":"system", password:'1234', ~~}
*/
//1. Array 순수 배열
/*
let person=["John", "Doe", 46];
document.write(person.length);
document.write("<hr>");
document.write(person[0]);
document.write("<hr>");
document.write(person[1]);
document.write("<hr>");
document.write(person[2]);
document.write("<hr>");
*/
/*
let person=[];
person["firstName"]="John";
person["lastName"]="Doe";
person["age"]=46;
document.write(person["firstName"]);//John
document.write("<hr>");
document.write(person["lastName"]);//Doe
document.write("<hr>");
document.write(person["age"]);//46
document.write("<hr>");
document.write(person[0]);//undefined
document.write(person[1]);//undefined
document.write(person[2]);//undefined
*/
/////////////////////////////////////////////////////////
//2. JSON 변수 선언 name:value 또는 key:value
let person = {"firstName":"John", "lastName":"Doe", "age":46};
//name에 ""생략가능
//let person = {firstName:"John", lastName:"Doe", age:46};
//JavaScript 접근
/*
document.write(person["firstName"]);//John
document.write("<hr>");
document.write(person["lastName"]);//Doe
document.write("<hr>");
document.write(person["age"]);//46
document.write("<hr>");
*/
//JSON 접근
document.write(person.firstName);
document.write("<hr>");
document.write(person.lastName);
document.write("<hr>");
document.write(person.age);
document.write("<hr>");
/////////////////////////////////////////////////////////
//3.
let persons = [
{"firstName":"John", "lastName":"Doe", "age":46},
{"firstName":"Tom", "lastName":"Doe2", "age":36},
{"firstName":"Jane", "lastName":"Doe3", "age":26},
];
document.write(persons.length);//3 존, 톰, 제인 3명의 요소로 이루어진 배열
for(n = 0 ; n < persons.length ; n++) {
document.write("<hr>");
document.write(persons[n].firstName);
document.write(persons[n].lastName);
document.write(persons[n].age);
}//for end
/*
document.write("<hr>");
document.write(persons[0]);//[object Object]
document.write("<hr>");
document.write(persons[1]);
document.write("<hr>");
document.write(persons[2]);
document.write("<hr>");
*/
'수업노트' 카테고리의 다른 글
| 카카오 우편번호, 맵 (1) | 2023.02.21 |
|---|---|
| 23.2.21(화) (0) | 2023.02.21 |
| 23.2.17(금) (0) | 2023.02.17 |
| 배열메소드 (0) | 2023.02.17 |
| 23.2.16(목) (0) | 2023.02.16 |