for-in
을 사용할 때는 중간에 undefined
요소는 출력되지 않는다shift
는 0번 인덱스 제거, unshift
는 0번 인덱스부터 밀어넣기new Array(5)
으로 배열 초기화 시, 5개 만큼의 빈 공간 확보new Array(1, 2, 3...)
쓰면, [1, 2, 3...]
나옴delete ${속성이름}
${속성이름} in ${Object}
new Object()
로도 초기화 가능, 근데 이렇게하면 밑에 obj.a = 10
이런식으로 써야한다.function
이나class
를 이용하여 커스텀 객체를 만들 수도 있다.const test1 = (params) => {
return 100 + params;
}
console.log(test1()); // NaN
console.log(test1(100, 99, 88)); // 200
function test2 () {
console.log(arguments.length); // 3, arugments는 화살표 함수에서는 작동하지 않는다.
eng = 50; // 전역변수
return 100;
}
console.log(eng); // undefined
console.log(test2(100, 99, 88)); // 100
console.log(eng); // 50
function test3 (...sus) {
// ...sus는 any[]타입이고, 아무거나 배열이 들어온다.
}
function test4 (params) {
return function (x = params) { return x + 1000 };
}
const res = test4(500);
console.log(res()); // 1500
console.log(test4(100)()); // 1100
function test5 () {
return function (x) { return x + 1000 };
}
console.log(test5()(300)); // 1300
const test6 = () => {
let count = 0;
const fn = (x) => {
count++;
console.log(count);
return x + 1000
}; // closure
return fn;
}
let fn = test6();
let su = fn(11); // count = 0;
fn(11); // count = 1;
fn(11); // count = 2;
fn(11); // count = 3;
// 객체로 사용하기 위한 함수
// 첫글자 대문자 권장
function Student (params) {
console.log('Student');
}
let st = Student(); // 일반 함수
let st2 = new Student(); // 객체 함수
console.log(typeof st); // undefined, 함수의 리턴값의 타입을 체크하기 떄문이다.
console.log(typeof st2); // object
st2.user_name = 'kim';
st2.age = 33;
st2.fn = function () {
return 100;
}
console.log(st2); // 객체 출력
function Person(name, age) {
this.user_name = name;
this.user_age = age; // var, let, const는 오브젝트의 속성이 될 수 없다.
}
let p = new Person('lee', 33);
console.log(p);
class Student {
}
let st = new Student();
st.user_name = 'kim';
st.user_age = 33;
st.fn = function () {
}
console.log(st);
class Person {
useel = '010'; // public
#user_tel2 = '02'; // private, 그냥 p 전체 찍으면 #user_tel2로 출력은 됨
static address = 'seoul'; // java의 static과 동일
constructor (name, age) {
this.user_name = name;
this.user_age = age;
}
sleep () {
this.study(); // 가능
return this.user_age / 3;
}
#study () { // private method
return 3;
}
get user_tel2 () {
return this.#user_tel2; // 이제부터 외부에서 p.user_tel2로 접근 가능. 함수가 아님에 주의한다.
}
static work() {
return 8;
}
}
let p = new Person('Yang', 44);
console.log(p); // tel, tel2, name, age 모두 나옴
console.log(p.user_tel2); // 02, getter 함수로 인해 접근 가능
console.log(Person.address); // static 변수 접근
console.log(Person.work()); // static 함수 접근
//------------------------------------------------------------------
class Member {
#tel;
constructor (num, id, pw, name, tel) {
this.num = num;
this.id = id;
this.pw = pw;
this.name = name;
this.#tel = tel;
}
set tel (tel) {
this.#tel = tel;
}
get tel() {
return this.#tel;
}
}
const m = new Member(1, 'id', 'pw', 'name', '010');
m.tel = '031' // setter 있으면 가능
console.log(m);
console.log(m.tel); // getter 있으면 가능
class Person {
money = 30000000000;
}
class Member extends Person {
...
constructor (num, id, pw, name, tel) {
super(); // 상속 받았다면, 반드시 해줘야 한다.
}
}
const m = new Member(1, 'id', 'pw', 'name', '010');
console.log(m.money); // 30000000000
// 1. property shorthand
// 이미 변수에 할당된 값들을 다른 객체에 할당하고자 할 때
var a = 1;
var b = 'hello';
var c = () => {
return 100;
}
var obj = { a, b, c };
console.log(obj); // 알아서 잘 들어가 있다. { a: 1, b: 'hello', c: f }
// 2. concise method
// 리터럴 객체 정의 시 함수 정의 간소화
obj = {
name: 'kim',
fn(){}, // 이렇게 써도 fn: f로 출력된다.
};
// 3. destructuring assignment (구조 분해 할당)
// 배열 정보와 객체 정보를 변수에 할당
let arr = [11, 22, 33, 44, 55];
let [x, y, ...z] = arr;
console.log(x, y, z); // 11, 22, [33, 44, 55]
let { name } = obj; // object도 ... 가능
console.log(name); // kim
const price = {
audi: 1000,
bmw: 2000,
sm5: 3000,
ps: 4000,
}
const { bmw, sm5, ps } = price;
// 4. spread syntax
const mem1 = { num: 1, id: 'mem1', pw: 'pw1', name: 'name1', tel: 'tel1', }
const mem2 = { num: 2, id: 'mem2', pw: 'pw2', name: 'name2', tel: 'tel2', }
const mem3 = { num: 3, id: 'mem3', pw: 'pw3', name: 'name3', tel: 'tel3', }
let members = [mem1, mem2, mem3];
const mem4 = { num: 4, id: 'mem4', pw: 'pw4', name: 'name4', tel: 'tel4', }
const mem5 = { num: 5, id: 'mem5', pw: 'pw5', name: 'name5', tel: 'tel5', }
let new_members = [mem4, mem5];
members = [...members, ...new_members]; // 이렇게 안하면 배열 전체가 원소 1개로 간주되어 들어간다.
console.log(members);
// 일반 데이터 정렬
let sus = [22, 11, 33];
sus.sort();
// 객체 내의 속성으로 정렬
members.sort((prev, next) => { // 원본배열 변경됨
if (prev.name === next.name)
return 0;
// return prev.name > next.name ? 1 : -1; // 순정렬
return prev.name < next.name ? 1 : -1; // 역정렬
});
console.log(members);
const copy_members = [...members].sort(); // 원본배열 변경없음
// 같은 속성을 갖는 객체 2개를 병합하기
const merge_member = Object.assign(mem1, mem5); // mem5의 복사 가능한 모든 객체를 mem1에 집어넣는다.
// 5. template literal
// 백틱
let su = 111;
let row = `Hello js ${su}`;
// 템플릿 리터럴 + 태그 함수
let student_name = 'kim';
let age = 20;
let tag_fn = (x, y, z) => {
console.log('x: ', x)
console.log('y: ', y)
console.log('z: ', z)
}
let fn = tag_fn`Student: ${student_name}, age:${age}`; // x에 ['Student: ', age:', ''], y에 'kim', z에 20 들어간다.
// 6. arrow function
// forEach, filter, map 등에 사용함. 너가 아는 그거
추가) Web worker라는 쓰레드 관련 Web API도 있다.
// js는 싱글스레드 기반이다.
function test(a, callback) {
console.log('test...');
console.log(a, callback);
setTimeout(() => {
callback(a + 10);
}, 100)
}
test(10, function (res) {
console.log(res);
});
// setTImeOut() 없다면
// test...
// f
// 10, f
// 있다면(위 코드)
// test...
// 10, f
// 20