Files
javascript-examples/Writerside/topics/Operator.md
2024-06-21 14:34:12 +09:00

96 lines
2.0 KiB
Markdown

# 연산자
대부분 자바의 연산자와 같습니다.
## 비교 연산자
- 동등 (==)
서로 값이 참입니다.
- 부등 (!=)
서로 다르면 참입니다.
- 일치 (===)
서로 값이 같고 자료형도 같으면 참입니다.
- 불일치 (!==)
서로 값이 다르거나 자료형이 다르면 참입니다.
```javascript
3 == "3" // true
3 === "3" // false
```
## 숫자화 연산자 (+)
피연산자를 숫자로 변환합니다.
```
+"3" // 3
+true // 1.
```
## typeof
typeof 연산자를 사용하면 변수의 자료형을 알 수 있습니다.
```javascript
let a = function () { };
let b = "Hello";
let c = 1;
let d = [1, 2, 3];
let e = {};
let f;
let g = true;
let h = null;
console.log(typeof a); // function
console.log(typeof b); // string
console.log(typeof c); // number
console.log(typeof d); // object. 배열은 array일 것 같지만 object입니다.
console.log(typeof e); // object
console.log(typeof f); // undefined
console.log(typeof g); // boolean
console.log(typeof h); // object. null은 object입니다.
```
## instanceof
객체의 형태를 확인할 때 사용합니다.
```javascript
let a = new String("Hello");
let b = "Hello";
console.log((a instanceof String) ? "yes" : "no"); // yes
console.log((b instanceof String) ? "yes" : "no"); // no
```
## in
객체에 어떤 속성이 있는 경우에 true를 반환합니다.
```javascript
let array = ["a", "b", "c"];
console.log((1 in array) ? "yes" : "no"); // yes
console.log(("b" in array) ? "yes" : "no"); // no. 배열의 경우 인덱스를 사용해야 합니다.
console.log(("length" in array) ? "yes" : "no"); // yes. Array객체에 length메서드가 있으므로.
let obj = { a: "A", b: "B", c: "C" };
console.log(("b" in obj) ? "yes" : "no"); // yes
console.log(("PI" in Math) ? "yes" : "no"); // yes. Math객체에 PI가 있으므로
```
## void
void 연산자는 식을 평가하지만, 값을 반환하고 싶지 않을 때 사용합니다.
```html
<a href="javascript:void(0)">
<a href="javascript:void(document.form.submit())">
```