728x90

✨ 내가 찾고자하는 Pattern(character or string etc)을 찾기에 유용한 helper method
(Pattern은 사실 Regular Expression(정규표현식)이지만 쉽게 표현하기 위해 사용하였다)

💻Example Code

const str = 'Hi There!!';
const matches = str.match(/[aeiou]/gi);

console.log( matches );
console.log( matches ? matches.length : 0 )

실행 결과(match된 내용과 배열의 길이)

😋 특히, 특정 문자열을 검색하는 알고리즘 문제를 풀거나, 개발을 할때 매우 유용하다. (단, RegExp를 잘 안다는 전제하에)
Vowels Algorithm(모음 찾기) 문제를 풀 때 잘 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match()

The match() method retrieves the result of matching a string against a regular expression.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.fromCharCode()  (0) 2020.01.01
Array.prototype.indexOf()  (0) 2020.01.01
String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
728x90

✨ 원하는 알파벳이나 숫자(0-9)의 아스키 코드(ASCII Code)를 알고 싶을 때, 사용하는 helper method
(e.g., str.charCodeAt(0)) 왼쪽처럼 알고 싶은 string의 index를 넣어서 사용한다. ()안에 아무것도 넣지 않으면 default 0
백준 11654번: 아스키 코드,  10809번: 알파벳 찾기 문제를 풀 때 사용하였다.

💻Example Code

const str = 'a';
const numStr = '1';

console.log( str.charCodeAt(0) );
console.log( numStr.charCodeAt(0) );
console.log( 'a'.charCodeAt(0) );

실행 결과('a'는 97, '1'은 49, 'A'는 65)

😋 JavaScript에서 string의 ASCII Code를 알고 싶을 때 사용하면 된다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt

 

String.prototype.charCodeAt()

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
728x90

✨ 문자열로 바꾸고싶을 때, toString() 대신에 사용하는 new String();
(e.g., const numToStr = new String(num)) 왼쪽처럼 선언하여 Number를 String으로 사용한다.

💻Example Code

const num = 77;
const numToStr = new String(num);

console.log( num );
console.log( numToStr );
console.log( numToStr.split('') ); // 활용 예시

실행 결과(Number 77, String 77, split된 77)

😋 [String: '77']의 정확한 의미는 모르겠지만, 일반 String처럼 사용 가능하다. 아마 Object가 생성되는 것 같다.
(조금 더 학습할 필요성이 있다)

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

 

String

The String global object is a constructor for strings or a sequence of characters.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.prototype.match()  (0) 2019.12.31
String.charCodeAt()  (0) 2019.12.31
new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
728x90

✨ 원하는 개수만큼 array를 선언하는 방법
(e.g., const arr = new Array(100)) 왼쪽처럼 선언하면 간단하게 100개의 array를 생성할 수 있다.

💻Example Code

const arr = new Array(100);

console.log( arr );
console.log( arr.length);

실행 결과(100개의 비어있는 Array 값, Array의 길이는 100)

😋 가끔 큰 index의 Array를 다룰 때, undefined보다는 하나의 값을 전체적으로 지정해주고 싶을 때가 있다. 그때 사용하면 된다.
백준 4673 셀프 넘버(Self Number)에서 유용하게 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

 

Array

The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.charCodeAt()  (0) 2019.12.31
new String()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
728x90

✨ Array.prototype.name() 을 지정하여 내가 원하는 helper method를 만들 수 있다.
(e.g., Array.prototype.name()) 왼쪽처럼 선언 후 arr.name()로 method를 실행시킬 수 있다.

💻Example Code

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

Array.prototype.sumTest = function(){
return this.reduce((acc, val) => {
return acc + val;
})
};

console.log( arr.sumTest() );

실행 결과(1+2+3+4+5=15)

😋 생활코딩에서 학습했었지만, 백준 4673번 문제를 풀면서 실전에서 사용해본 방법이다.

👉 실전에서 자주 사용할 수 있도록 조금 더 연습하고 이해할 필요가 있다.

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
728x90

✨ Array의 모든 index에 값을 한 번에 채워주거나, 원하는 구간만큼 값을 채워줄 수 있는 helper method

(e.g., arr.fill(false) or arr.fill(0, 2, 4)) 왼쪽처럼 Array의 모든 값을 false로 채우거나, index 2부터 3까지 0을 채워줄 수 있다.
(Array.prototype.slice()와 마찬가지로 구간을 지정할 때, end-1까지 진행된다는 점을 명심하자)

💻Example Code

const arr = [ 1, 2, 3, 4, 5, 6 ];

console.log( arr.fill(0, 1, 3) );

실행 결과(index 1부터 3까지 지정했지만, 2까지 변한 것을 볼 수 있다)

😋 매우 큰 Array의 값을 한 번에 초기화 해줄 때, 또는 원하는 index 구간만큼 값을 바꿔줄 때 매우 유용하다.
백준 4673번 셀프 넘버(Self Number)문제를 풀 때 사용했다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

 

Array.prototype.fill()

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
728x90

✨ pattern과 맞는 String을 교체해주는 helper method

(e.g., str.replace('dog', 'cat')) 왼쪽처럼 dog을 cat으로 교체하는 것이 가능하다.
간단하게 설명하자면,
첫 번째 parameter에는 RegExp(Regular Expressions) 또는 String을 넣을 수 있고(즉, 찾을 pattern)
두 번째 parameter에는 새로 넣을 new string을 넣을 수 있다(즉, 새로 넣을 replacement)

💻Example Code

1) 간단한 단어 교체

const str = 'Hi there!';
const afterReplace = str.replace('Hi', 'Hello');

console.log(afterReplace);

실행 결과(Hi가 Hello로 교체된 것을 볼 수 있다)

2) RegExp를 이용한 교체(alphabet만 남기기)

const strTwo = 'Hi! there~@!';
const afterReplaceTwo = strTwo.replace(/[^\w]/g, '');

console.log(afterReplaceTwo);

실행 결과(특수문자, 공백이 제거된 것을 볼 수 있다)

📌replace(/[^\w]/g, '')를 자세히 살펴보겠다.
1. RegExp의 시작과 끝은 /(slash)
2. []는 []안에 어느 것이라도 매치된다면 이라는 뜻이다. (다시 알아볼 필요가 있음)
3. ^ 는 무효화 시킨다는 뜻이다(반전이라고 생각하면 될듯하다)
4. \w은 글자와 숫자(alphanumeric)를 뜻한다.
5. g는 global이라는 뜻. 한 번 매치되어도 끝까지 매치되는 것을 찾게 한다.

즉, [^\w]을 이용해 글자와 숫자 이외의 모든 문자는 제거한다. 라고 보면 편하다.

😋 Anagrams(철자를 바꾼 말) Algorithm에서 공백, 구두점 그리고 특수문자를 제거하기 위해 사용하였다.
Regular Expressions은 문자열을 다루기에 매우 유용하다. 어렵기 때문에 하나씩 차근차근 쌓아가는 것이 필요하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

 

String.prototype.replace()

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

 

RegExp

The RegExp constructor creates a regular expression object for matching text with a pattern.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

 

Regular expressions

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), search

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.메소드() 만들기  (0) 2019.12.29
Array.prototype.fill()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
728x90

✨ object의 keys 또는 values를 array로 반환하는 helper method

💻Example Code

const obj = { a: 'something', b: 2, c: 3 };

console.log( Object.keys(obj) );
console.log( Object.values(obj) );

실행 결과(keys와 values가 array로 반환되는 것을 볼 수 있다)

😋 Anagrams(철자를 바꾼 말) Algorithm 에서 같은 종류의 철자가 사용되었는지 확인할 때 유용하게 사용하였다.
(Algorithm 카테고리의 Anagrams Algorithm 문제에서 확인 가능하다)
이 외에도 다양한 곳에서 사용 가능하다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

 

Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

 

Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.fill()  (0) 2019.12.29
String.prototype.replace()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
728x90

✨ 문자 또는 숫자를 순서대로 정렬할 때 사용하는 helper method

(e.g., strArr.sort() or numArr.sort((a, b) => a - b)) 문자를 sort 할 때, 10이 넘어가는 숫자를 sort할 때, 왼쪽처럼 사용법이 다르다.
Numbers는 Strings으로 변환되기 때문에, Unicode order에 따라 80이 9보다 앞에 위치한다.

💻Example Code

const strArr = [ 'c', 'b', 'a' ];
const numArr = [ 3, 33, 2, 22, 1, 11 ];

console.log( strArr.sort() );
console.log( numArr.sort() ); // For Example
console.log( numArr.sort((a,b) => a - b) );

실행 결과( 2번째 결과는 Number를 그냥 sort() 했을 때 결과이다)

😋 Anagrams(철자 순서를 바꾼 말) Algorithm에서 유용하게 사용 가능하며, 다양한 상황에서 사용 가능하다.

✔ sort((a, b) => a - b)로 숫자가 정렬되는 것을 Test 해보자

const numArr = [ 3, 2, 1, 11, 22 ,33 ];

function compare(a, b) {
console.log('a:'+a);
console.log('b:'+b);
return a - b; }

a가 b보다 작아서 negative가 나오는 경우 a는 b보다 낮은 숫자의 index를 갖고, 0은 변화 없음, 0보다 크면 a는 b보다 높은 index를 갖게 되는 식으로 정렬된다. 아마 선택 정렬(Selection Sort)과 비슷한 방식이 아닐까 생각해본다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 

Array.prototype.sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
728x90

✨ String의 알파벳을 대문자(toUpperCase()) 또는 소문자(toLowerCase())로 바꿔주는 helper method

(e.g., str.toLowerCase() or str.toUpperCase()) 왼쪽처럼 String 변수에 helper method를 붙여 사용한다.

💻Example Code

const strOne = 'abc';
const strTwo = 'ABC';

console.log( strOne.toUpperCase() );
console.log( strTwo.toLowerCase() );

실행 결과(소문자는 대문자로, 대문자는 소문자로 바뀐 걸 볼 수 있다)

😋 Anagrams(철자 순서를 바꾼 말)와 Vowels(모음 찾기) Algorithm 에서 유용하게 사용했다. 다양한 곳에서 활용이 가능하다.
활용된 내용은 위의 알고리즘 문제를 참고하시면 좋습니다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

 

String.prototype.toLowerCase()

The toLowerCase() method returns the calling string value converted to lower case.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

 

String.prototype.toUpperCase()

The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24

+ Recent posts