[Web] 08.JavaScript (Functions~JSON)
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
function name에는 letters, digits, underscores, 그리고 dollar signs을 포함할 수 있다. (variables 와 같은 규칙)
function function_name(prameter1, parameter2){
function contents //cond to be execute
}
Why Functions?
함수는 한 번 정의하면 반복해서 사용할 수 있기 때문에 사용을 한다.
각각 다른 arguments로 각각 다른 결과 값을 얻어낼 수 있다.
Example:
<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
</script>
Result: The temperature is 25 Celsius
Functions Variables
Function 은 변수의 값으로도 사용될 수 있다.
Function 내부에 선언된 변수는 Local 변수로 지정되어, 함수 내에서만 접근이 가능하기 때문에 사용에 유의해야한다.
JavaScript Objects
JavaScript의 Objects에 관하여 이해하기 쉽게 설명하기 위해서 예시를 하나 들어보려고 한다.
실제 환경에서, 자동차를 예시로 들 수 있다.
자동차는 무게나 색 과 같은 properties, 그리고 출발이나 정지와 같은 methods로 구성되어 있다.
모든 자동차는 같은 properties를 가지고 있지만 그 값은 차마다 다르다.
또한 모든 자동차는 모두 methods가지지만, 각각의 methods는 다르게 행동한다.
JavaScript에서는 어떨까?
Objects는 Variables와 같다. 하지만 object는 많은 값을 담을 수 있는 공간이다.
Example:
<p id="demo"></p>
<script>
// Create an object:
var car = {type:"Fiat", model:"500", color:"white"};
// Display some data from the object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>
위에 예시에서 type, model, color는 앞서 말했던 Property에 해당한다.
그리고 그에 해당하는 Fiat, 500, white는 Property Value에 해당한다.
The this Keyword
In a function definition, this refers to the "owner" of the function.
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
HTML Events
Event | Description |
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
이벤트를 활용하면 더욱 많은 기능을 사용할 수 있다.
JavaScript Strings
JavaScript에서 String은 ' 작은 따옴표나 " 큰 따옴표를 사용한다.
String Length
length property를 이용하면 string의 길이를 알아낼 수 있다.
<p>The length property returns the length of a string:</p>
<p id="demo"></p>
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;
</script>
Escape Character
Code | Result | Description |
\' | ' | Single quote |
\" | " | Double quote |
\\ | \ | Backslash |
\b | Backspace | |
\f | Form Feed | |
\n | Newline | |
\r | Carriage Return | |
\t | Horizontal Tabulator | |
\v | Vertical Tabulator |
Example:
<p>The escape sequence \" inserts a double quote in a string.</p>
<p id="demo1"></p>
<script>
var x = "We are the so-called \"Vikings\" from the north.";
document.getElementById("demo1").innerHTML = x;
</script>
<p>The escape sequence \' inserts a single quote in a string.</p>
<p id="demo2"></p>
<script>
var x = 'It\'s alright.';
document.getElementById("demo2").innerHTML = x;
</script>
<p>The escape sequence \\ inserts a backslash in a string.</p>
<p id="demo3"></p>
<script>
var x = "The character \\ is called backslash.";
document.getElementById("demo3").innerHTML = x;
</script>
JavaScript Strings Methods
Code | Result | |
str.length | returns the length of a string | |
str.indexof() | returns the index of the first occurrence of a specified text in a string | |
str.lastIndexOf() | returns the index of the last occurrence of a specified text in a string | |
str.search() | searches a string for a specified value and returns the position of the match | |
str.slice(start,end) | slice out a portion of a string | |
str.substring() | cannot accept negative indexes | |
str.substr() | the second parameter specifies the length of the extracted part. | |
str.replace() | replaces a specified value with another value in a string | |
str.toUpperCase() | convert to upper case | |
str.toLowerCase() | convert to lower case | |
str.concat() | instead of the plus operator | |
str.trim() | remove whitespace from both sides of a string | |
str.charAt() | returns the character at a specified index in a string | |
str.charCodeAt() | returns the unicode of the character at a specified index in a string |
Example:
//length
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
//indexof()
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
//lastindexof()
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
//search()
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
//slice()
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
//substring()
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
//substr()
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
//replace
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
//toUpperCase()
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
//toLowerCase()
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
//concat()
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
//trim
var str = " Hello World! ";
alert(str.trim());
JavaScript Numbers
JavaScript has only one type of number. Numbers can be written with or without decimals.
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
If you add two numbers, the result will be a number.
If you add two strings, the result will be a string concatenation.
If you add a string and a number, the result will be a string concatenation.
Numeric Strings
var x = 100; // x is a number
var y = "100"; // y is string
//JavaScript will try to convert strings to numbers in all numeric operations:
var x = "100";
var y = "10";
var z = x/y; // z will be 10
//This will also work:
var x = "100";
var y = "10";
var z = x * y; // z will be 1000
//And this will work:
var x = "100";
var y = "10";
var z = x - y; // z will be 90
//But this will not work
var x = "100";
var y = "10";
var z = x + y; // z will not be 110( it will be 10010)
JavaScript Number Methods
The toString() Method
toString() method 는 숫자열을 문자열로 변환해준다.
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
The toExponential() Method
toExponential() method는 지수 표기법을 사용해 숫자를 반올림하고 쓴 문자열을 반환해준다.
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
The toFixed() Method
toFixed() 는 지정된 소수 자릿수로 된 숫자로 문자열을 반환
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
JavaScript Arrays
자동으로 배열을 정렬해주는 함수들을 사용할 수 있다.
sort() : 배열을 알파벳 순으로 나열하여 정렬한다.
reverse(): 배열의 순서를 역으로 정렬한다.
JavaScript Array Iteration Methods
말 그대로 배열을 반복하는 함수들이다.
arr.forEach() : 각 배열 element들에 대한 함수를 호출한다. 이를 통해 배열의 내용들을 출력 가능하다.
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt = txt + value + "<br>";
}
arr.map(): 각 배열의 element들에 대해 사용자가 넣은 기능을 수행하도록 하여 새로운 배열을 만든다.
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
arrfilter(): 배열들의 각 element들에 대해서 조건들을 통과하는 새로운 배열을 만든다.
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
arr.indexOf(): 배열에서 원하는 element를 찾아서 그 위치(index)를 return한다.
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
JavaScript Random
Math.random(); : 0~1 사이의 숫자 중 랜덤 숫자를 return
Math.floor(): 임의의 정수 반환
Math.floor(Math.random() * 10); // returns a random integer from 0 to 9
Math.floor(Math.random() * 11); // returns a random integer from 0 to 10
Math.floor(Math.random() * 100); // returns a random integer from 0 to 99
JavaScript Use Strict
Use Strict 를 사용할 경우 선언되지 않는 변수는 사용할 수 없도록 된다.
- 선언하지 않는 객체의 사용이 불가능하다.
- 변수, 객체를 삭제 불가능하다.
- 기능 삭제도 불가능하다.
- 매개 변수의 이름을 복제할 수 없다.
- 숫자 앞에 0을 사용하는것이 불가능(ex 010).
- 읽기 전용 속성에 쓰는것이 불가능하다.
- get-only속성에 쓰는것이 불가능하다.
- this의 키워드가 다르게 작동함 → 객체를 지정하지 않을 경우 undefined함수가 반환한다.
Example:
"use strict";
myFunction();
function myFunction() {
y = 3.14; // This will also cause an error because y is not declared
}
JavaScript JSON
JSON : Java Script Object Notation, 간단한 데이터 교환 형식