<script>
function 함수이름(){
...실행할 구문 ...
}
</script>
<script>
function sayHello() {
document.write("<h1>안녕하세요</h1>");
document.write("<h1>자바스크립트</h1>");
}
</script>
<script>
함수이름();
</script>
<script>
sayHello();
sayHello();
sayHello();
</script>
결과값 :
안녕하세요
자바스크립트
안녕하세요
자바스크립트
안녕하세요
자바스크립트
<script>
function 함수이름(파라미터){
..실행할 구문
}
</script>
<script>
함수이름(파리미터);
</script>
<script>
function f(x){
var y = x+1;
document.write("<h1>" + y + "</h1>")
}
f(2);
f(3);
f(10);
</script>
결과 값 :
3
4
11
<script>
function 함수이름(파라마토1, 파라미터2){
실행할 구문
}
</script>
<script>
함수이름(파리미터1, 파라미터2)
</script>
<script>
function f(x,y){
var z = x + y;
document.write("<h1>" + z + "</h1>");
}
f(2,1);
f(5,6);
f(2,4);
</script>
결과 값 :
3
11
6
<script>
function f(x){
return x + 1;
}
</script>
<script>
var y = f(5);
</script>
<script>
function sum(x, y){
var z = x + y ;
return z;
}
function printResult(x, y) {
var result = sum(x, y)
document.write("<h1>" + result + "</h1>");
}
printResult(7,10);
</script>
결과 값 :
17
<script>
(function(){
let i = 0;
while(i < 10){
document.write(i);
i += 1;
}
})();
</script>
<script>
// numbering 이라는 변수가 함수를 갖게된다.
// function numbering(){..}과 같다.
let numbering = function () {
let i = 0;
while( i < 10){
document.write(i);
i += 1;
}
}
numbering();
</script>
<script>
let foo = () => {console.log('foo function')}
foo();
</script>
<script>
let foo2 = x => document.write(x);
foo2('user');
let sayHi = () => alert("안녕하세요");
sayHi();
</script>
<script>
let user = (a,b) => a+b;
document.write(user(1,3));
document.write("<br>")
let user2 = (a,b) => {return a + b} // 중괄호가 있으면 무조건 return이 있어야 한다.
document.write(user2(3,4));
document.write("<br>")
let user3 = (a,b) => {a + b}
document.write(user3(3,4));
document.write("<br>")
let user4 = (a,b) =>{
let c= 3;
return a + b + c;
}
document.write(user4(10,11));
document.write("<br>")
let user5 = n => n *2;
/*
function user5(n){
return n*2;
}
*/
document.write(user5(3));
</script>
결과 값 :
4
7
undefined
24
6
<script>
() => {
const x = 10;
return x;
}
</script>
여러줄이면 중괄호 생략 할수 없음.
변수의 NaN여부를 검사하는 함수
숫자인지 검사하기
<script>
let v1 = "가나다라";
let v2 = "123456";
let is_num1 = !isNaN(v1);
let is_num2 = !isNaN(v2);
if (is_num1) {
document.write("<h1>" + v1 + "는 숫자이다</h1>");
}else{
document.write("<h1>" + v1 + "는 숫자가 아니다</h1>");
}
if (is_num2) {
document.write("<h1>" + v2 + "은 숫자이다</h1>");
}else{
document.write("<h1>" + v2 + "은 숫자가 아니다</h1>");
}
</script>
결과 값 :
가나다라는 숫자가 아니다
123456은 숫자이다