Array.prototype.at(index);

Array.prototype.at(index); method는 parameter로 반환받고 싶은 element의 index값을 넘겨주며, parameter로 음수와 정수 모두 사용가능하며 음수인 경우 배열의 뒤에서부터 indexing한다.

const array = ["apple", "banana", "lemon"];

console.log(array.at(0)); // "apple"
console.log(array[0]); // "apple"

console.log(array.at(-1)); // "lemon"
console.log(array[array.length -1]); // "lemon"

 

Array.prototype.concat(elements);

Array.prototype.concat(elements); method는 기존 배열에 인자로 들어온 요소나 배열을 합하여 새로운 배열을 반환하는 메서드이다.

- 기존 배열을 변경하지 않는다.

- 인자가 추가된 새로운 배열을 반환한다.

const array = ["apple", "samsung"];
const array2 = ["LG"];

console.log(array.concat(array2)); // [ "apple", "samsung", "LG" ]
console.log(array); // ["apple", "samsung"]

const array3 = array.concat(array2);
console.log(array3); // ["apple", "samsung", "LG"]

 

Array.prototype.copyWithin(target, start [,end]);

Array.prototype.copyWithin(target, start [,end]); method는 배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮은 후 해당 배열을 반환한다. 이때 배열의 길이는 변경되지 않는다.

const array = ['a','b','c','d','e','f'];
const array2 = ['a','b','c','d','e','f','g'];
array.copyWithin(2,5); // ['a','b','f','d','e','f']
array2.copyWithin(1,2,5); // ['a','c','d','e','e','f','g']

console.log(array); // ['a','b','f','d','e','f']
console.log(array2); // ['a','c','d','e','e','f','g']

 

Array.prototype.entries()

Array.prototype.entries(); method는 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Iterator 객체를 반환한다.

const array = ["apple", "lemon", "orange", "strawberry"];
const iterator = array.entries();

console.log(iterator.next().value)); // [0, "apple"] => Array
console.log(iterator.next().value)); // [1, "lemon"] => Array
console.log(iterator.next().value)); // [2, "orange"] => Array
console.log(iterator.next().value)); // [3, "strawberry"] => Array
console.log(iterator.next().value)); // undefined

 

Array.prototype.every(function)

Array.prototype.every(function) method는 배열의 모든 요소가 주어진 판별함수를 통과하는지 테스트하는 메서드로, 반환값은 boolean이다.

const isTenOver = (element) => element > 10;
const array = [11,12,14,20];

array.every(isTenOver); // true

 

Array.prototype.fill(value [, start [ , end] ] );

Array.prototype.fill() method는 배열의 시작부터 끝 이전까지 정적인 값 하나로 모두 채우는 메서드이다.

* parameter

- value : 배열을 채울 값

- start : 시작 인덱스 기본값 0

- end : 끝 인덱스 기본값 array.length

const array = [1,2,3,4,5];

array.fill(5);
console.log(array); // [5,5,5,5,5]

array.fill('a',2,4); // [5,5,'a','a',5]

 

Array.prototype.filter( callback(element [ , index [ , array ] ] ) [ , thisArg ]);

Array.prototype.filter() 메서드는 매개변수로 주어진 callback 함수의 테스트를 통과한 요소들만 모아 새로운 배열을 반환한다. 

- callback : true 를 반환하면 요소를 유지 false를 반환하면 요소를 버린다. 

- element : 현재 처리할 요소

- index : 현재 처리할 요소의 인덱스

- array : filter를 호출한 배열

- thisArg : callback을 실행할 때 this로 사용하는 값

const number = [1,2,3,"4",5,6];
const newNumber = number.filter( (element) => typeof element === "number" );

console.log(newNumber); // [1,2,3,5,6]

 

Array.prototype.find( callback [ , thisArg ] )

Array.prototype.find() 메서드는 주어진 판별함수를 만족하는 첫 번째 요소의 값을 반환한다. 해당하는 요소가 없다면 undefined를 반환한다.

const array = ["a",3,4,"b"];
const found = array.find((element) => typeof element === "number");

console.log(found); // 3

const fruits = [
	{ name : "banana", quantity : 3 },
    { name : "apple", quantity : 5 },
    { name : "lemon", quantity : 2 }
];

function findApple(fruit){
	return fruit.name === "apple";
}

const Apple = fruits.find(findApple);
console.log(Apple); // {name: 'apple', quantity: 5}

 

Array.prototype.findIndex( callback(element [ , index [ , array ] ]) [ , thisArg ] );

Array.prototype.findIndex() 메서드는 주어진 판별함수를 만족하는 첫 번째 요소의 인덱스를 반환한다. 배열의 첫 번째 요소가 존재하지 않는다면 -1을 반환한다.

const fruits = [
	{ name : "banana", quantity : 3 },
    { name : "apple", quantity : 5 },
    { name : "lemon", quantity : 2 }
];

function findApple(fruit){
	return fruit.name === "apple";
}

function findCherry(fruit){
	return fruit.name === "cherry";
}

const Apple = fruits.findIndex(findApple);
console.log(Apple); // 1

const Cherry = fruits.findIndex(findCherry);
console.log(Cherry); // -1

 

Array.prototype.forEach(callback(currentValue [ , index [ , array ]] ) [ , thisArg ] );

Array.prototype.forEach(); method는 주어진 함수를 배열 요소 각각에 대해 실행한다.

const array = ["apple", "banana", "lemon", "cherry"];
array.forEach( fruit => console.log(fruit) );
// "apple"
// "banana"
// "lemon"
// "cherry"

 

Array.prototype.includes(valueToFind [, fromIndex ]);

Array.prototype.includes(); method는 배열이 특정 요소를 포함하고 있는지를 판별한다. 반환값은 boolean이다.

- valueToFind : 찾고자하는 요소

- fromIndex : 검색을 시작할 위치 

const array = ["apple", "banana", "lemon"];
array.includes("apple"); // true
array.includes("cherry"); // false
array.includes("apple",0); // true
array.includes("apple",2); // false
array.includes("lemon",1); // true

 

Array.prototype.indexOf(searchElement [, fromIndex])

Array.prototype.indexOf(element, [fromIndex]); 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번재 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.

const array = [ "a", "b", "c", "d", "e" ];
console.log( array.indexOf("e") ); // 4
console.log( array.indexOf("f") ); // -1
console.log( array.indexOf("a",2) ); // -1

 

Array.isArray(obj);

Array.isArray() 메서드는 메서드의 인자가 Array인지 아닌지를 판별한다. 반환값은 Boolean이다.

const array = [1,2,3];

Array.isArray(array); // true
Array.isArray(3); // false

[ + ] 계속 추가할 예정

Array.prototype.join()

Array.prototype.map()

...

push()

pop()

reduce()

reverse()

shift()

slice()

some()

sort()

unshift()

toString()

values()

 

 

728x90

async/await ?

async/await 은 자바스크립트에서 Promise 객체를 통해 처리하던 비동기 처리를 더 쉽고, 편하게 처리/사용할 수 있도록 나온 ECMAScript 2017 문법이다.

 

async/await 기본문법

async function 함수명() {
	await 비동기처리메서드명();
}

비동기 처리메서드가 꼭 프로미스 객체를 반환해야 await가 의도한 대로 작동한다.

promise 앞에 await keyword를 붙이면, javascript는 promise가 처리될 때 까지 대기하고, 처리가 완료되면 조건에 따라 동작한다.

1. 에러발생 => 예외 생성

2. 에러 미발생 => 프로미스 객체의 result 반환

 

async/await 예외처리

async function 함수명(){
	try{
    	...
    }
    catch(err){
    	console.log(err);
    }
}

try/catch 로 예외처리

 


[ + ] 나중에 내용 더 추가할 예정

728x90

'Language > Javascript' 카테고리의 다른 글

[ Javascript ] setTimeout, setInterval  (0) 2022.07.27
[ Javascript ] Array.prototype Methods  (0) 2022.03.08
[ Javascript ] Promise  (0) 2022.03.06
[ Javascript ] Class { ES6 (ES2015) }  (0) 2022.02.20
[ Javascript ] Set Object  (0) 2022.01.11

Asynchronous ( 비동기 )적 처리는 작업을 요청하지만 결과는 그 자리에서 꼭 받지 않아도 되는 데이터 처리 방식

Synchronous ( 동기 )적 처리는 작업을 요청함과 동시에 작업의 결과를 그 자리에서 받을 수 있는 데이터 처리 방식


Promise

Javascript Engine은 Single Thread로 동시에 두가지 작업을 할 수 없다. 이러한 Javascript가 비동기 처리를 할 수 있게 나온 것이 Promise이다.

 

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타낸다. 

► 코드의 실행 흐름에서 비동기처리를 유연하게 처리하기 위한 API

 

Promise 객체 상태

1. 대기 ( pendding ) : 이행하지도, 거부하지도 않은 초기 상태.

2. 이행 ( fulfilled ) : 연산이 성공으로 완료됨.

3. 거부 ( rejected ) : 연산이 실패함.

 

Promise.prototype.then() 및 Promise.prototype.catch() 메서드의 반환 값은 새로운 Promise로서 서로 연결할 수 있다. 



 

Promise 객체는 return 값으로 새로운 Promisse를 만들며 이는 서로 연결할 수 있다. 

 

Pendding  대기

new Promise() 메서드를 호출했을 때 pendding ( 대기 ) 상태이다.

Promise 메서드의 인자는 콜백함수이며, 콜백함수의 인자는 resolve, reject 이다.

new Promise(function(resolve, reject) {
	...
});

 

Fulfilled 이행

new Promis() 메서드의 콜백함수에서 resolve()를 수행하면 Fulfilled 이행 상태가 된다.

new Promise(function(resolve, reject) {
	resolve(); // 수행한 경우 fulfilled state
});

이행이 되면 .then() 메서드를 통해서 return 값을 받을 수 있다.

 

Rejected 실패

new Promise() 메서드의 콜백함수에서 reject()를 호출하면 Rejected 실패 상태가 된다.

new Promise(function(resolve, reject) {
	reject(); // rejceted state가 된다.
});

reject 반환값은 .then.catch(error)를 통해서 받을 수 있다.

 

 

참고 :

https://joshua1988.github.io/web-development/javascript/promise-for-beginners/

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise

728x90

'Language > Javascript' 카테고리의 다른 글

[ Javascript ] Array.prototype Methods  (0) 2022.03.08
[ Javascript ] async/await  (0) 2022.03.07
[ Javascript ] Class { ES6 (ES2015) }  (0) 2022.02.20
[ Javascript ] Set Object  (0) 2022.01.11
[ Javascript ] Map Object  (0) 2022.01.11

Class

Javascript ES6 이전까지는 비슷한 종류의 객체를 많이 만들어내기 위해 생성자를 사용해 왔으나, ES6 이후에서 Class라는 개념이 도입되면서 Class가 생성자의 기능을 대체하게 된다. 

객체지향언어 ( ex : JAVA, C++ ... 등 ) 을 공부했던 사람들이라면 바로 이해하고 익힐 수 있을 것이라고 생각한다. 

 

Class를 사용하는 가장 큰 이유는 재사용성이다.

예시로 여러 동물들에 대한 정보를 저장해야 한다고 가정할 때 동물들은 기본적으로 "name", "age"라는 속성을 갖고, "walk"라는 method를 갖는다고 가정을 한다면 동물마다 하나하나 해당 속성을 정의하게 되면 동물의 수가 적을 경우에는 간단할 수 있지만 100마리, 1000마리, 10000마리 ... 를 정의한다고 가정하면 매우 시간이 많이 들고 코드의 수가 길어지며 가독성이 떨어질 수 있다.

이렇게 속성이 중복되는 경우 하나의 Class로 해당 속성들을 정의하면 코드가 훨씬 짧아질 뿐만아니라, 가독성 또한 상승된다. 

아래 코드가 그 예시이다.

class Animal {
	constructor(name, age) {
    	this.name = name;
        this.age = age;
        this.position = 0;
    }
	
    Walk() {
    	this.position += 1;
    }
}

const Rabbit = new Animal("토끼",3);
const Dog = new Animal("개",2);

console.log(Rabbit);
Rabbit.Walk();
console.log(Rabbit.position);

console.log(Dog);

 

console.log 출력 값


Class 기본 문법

Class 생성하기

class 생성하는 것은 간단하다. class 다음에 만들고자 하는 class 이름을 입력한 후 중괄호로 닫아주면 된다.

class "className" {

}

let classTest = new "className"();

console.log(classTest);

// console.log 결과 "className" {}

 

Class 초깃값 설정

class의 초깃값은 constructor라는 생성자를 이용하여 설정할 수 있다. class 내부에는 한 개의 constructor만 존재할 수 있으며, 2개 이상 선언 시 아래와 같은 Syntax Error가 발생한다.

Uncaught SyntaxError: A class may only have one constructor

class Animal {
	constructor( name , age , position ) {
    	this.name = name;
        this.age = age;
        this.position = position;
    }
}

const Rabbit = new Animal("rabbit",2,5);

console.log(Rabbit);
// Animal { name : "rabbit", age : 2, position : 5 }

 

Class method 생성/사용

class의 method는 function 형식으로 만들어 준다. 해당 메서드를 사용할 경우 " 객체가 담긴 변수명.메소드() " ( Rabbit.Walk() ) 형식으로 호출 가능하다. 

class Animal {
	constructor( name , age , position ) {
    	this.name = name;
        this.age = age;
        this.position = position;
    }
    
    Walk(){
    	this.position += 1;
    }
}

const Rabbit = new Animal("rabbit",2,5);

console.log(Rabbit);
// Animal { name : "rabbit", age : 2, position : 5 }

Rabbit.Walk();
Rabbit.Walk();

console.log(Rabbit);
// Animal { name : "rabbit", age : 2, position : 7 }

 

class내부에서 메소드를 정의하는 것이 아닌 class 외부에서도 메소드 정의가 가능하다. 그러나 class 자체에 추가하는 것이 아닌 class 객체를 담고 있는 변수에서 추가하는 것이기 때문에 해당 변수외의 또 다른 Animal class 객체를 담고 있는 변수의 경우 외부에서 정의한 메소드 사용이 불가능하다. 

아래 코드를 참고하여 보자.

class Animal {
    constructor( name , age , position ) {
        this.name = name;
        this.age = age;
        this.position = position;
    }

    Walk(){
        this.position += 1;
    }
}

const Rabbit = new Animal("rabbit",2,5);
Rabbit.Jump = function(){
    return `${this.name} jump`
}

console.log(Rabbit);
// Animal { name : "rabbit", age : 2, position : 5 }

Rabbit.Walk();
console.log(Rabbit.Jump()); // rabbit jump

console.log(Rabbit);
// Animal { name : "rabbit", age : 2, position : 6 }

 

extends 상속

class에는 상속이라는 개념을 사용할 수 있다. 예제를 보면 더 쉽고 빠르게 이해할 수 있을 것이다. 

상속받은 class의 속성, method를 모두 사용할 수 있다. 

class Animal {
    constructor( name , age , position ) {
        this.name = name;
        this.age = age;
        this.position = position;
    }

    Walk(){
        this.position += 1;
    }
}

class Rabbit extends Animal {
	Jump(){
    	console.log("Rabbit Jump");
    }
}

class Dog extends Animal {
	Bark(){
    	console.log("Wang Wang!");
    }
}

const dog = new Dog("meonzy",3,10);
const rabbit = new Rabbit("tosun",2,9);

dog.Bark();
dog.Walk();
rabbit.Jump();
rabbit.Walk();

 

super 키워드

super 키워드를 사용하여 자식 class에서 부모 class를 호출할 수 있다. 주로 constructor에서 많이 사용한다.

class Animal {
    constructor( name , age , position ) {
        this.name = name;
        this.age = age;
        this.position = position;
    }

    Walk(){
        this.position += 1;
    }
}

class Rabbit extends Animal {
	constructor(name, age, position, jumpSkill){
    	super(name,age,position);
        this.jumpSkill = jumpSkill;
    }
	Jump(){
    	console.log(`Rabbit ${this.jumpSkill} jump`);
    }
}

class Dog extends Animal {
	Bark(){
    	console.log("Wang Wang!");
    }
}

const dog = new Dog("meonzy",3,10);
const rabbit = new Rabbit("tosun",2,9,"100%);

dog.Bark();
dog.Walk();
rabbit.Jump();
rabbit.Walk();

 

참고 :

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

728x90

'Language > Javascript' 카테고리의 다른 글

[ Javascript ] async/await  (0) 2022.03.07
[ Javascript ] Promise  (0) 2022.03.06
[ Javascript ] Set Object  (0) 2022.01.11
[ Javascript ] Map Object  (0) 2022.01.11
[ Javascript ] Array.prototype.includes()  (0) 2022.01.11

+ Recent posts