웹마스터 팁

Part1-3(3장). 자바스크립트연산자2
(논리연산자, 비트, 삼항연산자, 기타연산자)

 

1. 논리연산자
논리and : &&
논리or : ||

 

 

<예제>

Javascript3-1.html

 

<html>
<head><title> </title>
<script language="javascript">
<!--
a = 'A';
b = 'B';
document.write("자바스크립트예제"+"<br>");
c = !2 || 3 && !0
document.write(c +"<br>");
c = a < b && a == b
document.write(c +"<br>");
c = a < b || a == b
document.write(c +"<br>");
//-->
</script>
</head>
<body>
</body>
</html>

 

#실행결과

자바스크립트예제

true

false

true

 

 

 

2. 비트연산자(1) 쉬프트연산자
비트를이동시키는연산자로오른쪽으로의이동과왼쪽으로의이동하는두가지종류의방식이있다.

 

>> 오른쪽으로 이동

예) 5>>2 의미 : 5의 이진수표현에서 오른쪽으로 2칸 쉬프트

<< 왼쪽으로 이동

예)5>>2 의미 : 5의 이진수 표현에서 왼쪽으로 2칸 쉬프트

 

 

<예제>

Javascript3-2.html

<html>
<head><title> </title>
<script language="javascript">
<!--
a = 5;
b = 2;
c = a >> b;
document.write("자바스크립트예제"+"<br>");
document.write(a + "<br>");
document.write(b + "<br>");
document.write(c + "<br>");
//-->
</script>
</head>
<body>
</body>
</html>

 

#실행결과

자바스크립트예제

5

2

1

 

 

2. 비트연산자(2) 비트논리연산자
&(비트AND), |(비트OR), ^(비트XOR), ~(비트NOT) 등이있다.

 

<예제>

Javascript3-3.html

<html>
<head><title> </title>
<script language="javascript">
<!--
a = 30;
b = 25;
c = a & b;
document.write("자바스크립트예제"+"<br>");
document.write(a + "<br>");
document.write(b + "<br>");
document.write(c + "<br>");
//-->
</script>
</head>
<body>
</body>
</html>

 

#실행결과

자바스크립트예제

30

25

24

 

 

2. 비트연산자(1) 비트not연산자
~ (틸더)
이진표현의비트를만대로만든다

 

<예제>

Javascript3-4.html

<html>
<head><title> </title>
<script language="javascript">
<!--
a = -1;
b = -4;
c = ~a ;
document.write("자바스크립트예제"+"<br>");
document.write(a + "<br>");
document.write(b + "<br>");
document.write(c + "<br>");
c = ~b ;
document.write(c + "<br>");
//-->
</script>
</head>
<body>
</body>
</html>

 

#실행결과

자바스크립트예제

-1

-4

0

3

 

 

 

3. 3항연산자
항이3개가필요하기때문에3항연산자라고함.
연산원리는그림과같음

 

<예제>

Javascript3-5.html

<html>
<head><title> </title>
<script language="javascript">
<!--
x = 10;
y = 20;
z = ( x > y ? x : y);
document.write("자바스크립트예제"+"<br>");
document.write(x + "<br>");
document.write(y + "<br>");
document.write(z + "<br>");
z = ( y > x ? x : y);
document.write(z + "<br>");
//-->
</script>
</head>
<body>
</body>
</html>

 

#실행결과

자바스크립트예제

10

20

20

10

 

4. 기타연산자(문자연결연산자)
+ 기호를사용함
예) A + “res”(A에10 이저장된경우)
10res가출력됨